I have successfully exported the data I receive from the rows I read into a csv file, but I need to set a Header for each row so I can identify them. I have tried this:
file = open("llistaClients.csv", "w")
file.write("ID;NAME;PHONE;EMAIL;STREET;CITY")
for row in rows:
print(row['id'], row['name'], row['phone'], row['email'], row['street'], row['city'], sep="\t")
dades = str(row['id']) + ";" + str(row['name']) + ";" + str(row['phone']) + ";" + str(row['email']) \
+ ";" + str(row['street']) + ";" + str(row['city']);
file.write(dades + "\n")
Without this file.write("ID;NAME;PHONE;EMAIL;STREET;CITY") it all works perfectly:
But if I try to use it, it just won't open with Excel. But, if I open the same file with the notepad it indeed applies this header.
I have a potential fix which lets me put the header without problem using: (other fields)
import csv
with open("llistaProductes.csv","w") as csvfile:
fieldnames = ['id','name','list_price','create_date'];
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader();
for row in rows:
#print(dict(row))
print(row['id'], row['name'], row['list_price'], row['create_date'], sep="\t")
writer.writerow({'id': row['id'], 'name': row['name'],
'list_price': row['list_price'], 'create_date': row['create_date']})
But using this I get this in excel:
It doesn't separate between columns.. Which is not bad, but not how it should do..
So the question here is, why can't I use the first method properly? And if the second is the one I should use how to separate the columns. Thank you.


file.write("ID;NAME;PHONE;EMAIL;STREET;CITY\n")