Coder101 Coder101 - 9 days ago 5
Python Question

Python saving data to a csv file

I normally use txt files but i need to use a csv i based this off how i do txt files and i am not sure what i am doing wrong can anyone help me please.

Home = "Road"
House = 5

def Save(Home,House):
Saved=open('Saved.csv', 'a')
Saved.write(Home+House+"/n")
Saved.close()

Save(Home,House)


I get this error

File "F:/Pygame/Test12.py", line 74, in Save
Saved.write(Home+House+"/n")
TypeError: cannot concatenate 'str' and 'int' objects

Answer

1) that's not a .csv file.

2) in python, you cannot concatenate integers with strings without prior conversion.

3) doing this: Home+str(House) would be legal, but when you want to read back your file you have to separate both fields (you provided no way of separating them)

Here's a code which would create a real csv file:

import csv
def Save(Home,House):
    with open('Saved.csv', 'a') as Saved:
       cw = csv.writer(Saved)
       cw.writerow([Home,House])

when you compose your row, you can put any data you want, the csv module will convert it to string if needed.

BTW to read it back, use a csv.reader and iterate through the rows. Since you know the datatype, you can convert 2nd column to int directly.

with open('Saved.csv', 'r') as Saved:
   cr = csv.reader(Saved)
   for row in cr:
       Home = row[0]
       House = int(row[1])
       # now you have to do something with those variables :)