Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Error on writing to csv file
-
@jokiehints, first check if the file exists. Only
writeheader
if it did not. -
@jokiehints Oups, I was able to help you for technical problem but, sincerely, I don't know anything about csv 😢
I hope somebody else will advice you. I'll follow your topic and if nobody doesn't (but I'ld be very surprised if it happens), I'll try to help you. -
@cvp OK thanks, I understand. Ik hope somewone else can give me the tips I need.
-
@jokiehints Really not sure that I correctly understood, if not, sorry and forget this post
import csv import os values = {} def set(fieldname,value): values[fieldname] = value set('geb_dag',10) set('geb_maand',19) file = 'data.csv' header = not os.path.exists(file) with open(file, 'a', newline='') as csvfile: fieldnames = ['geb_dag','geb_maand'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) if header: writer.writeheader() writer.writerow(values)
-
@cvp Thank you so much for your effort. Unfortunately this code isn't working for the format I want to get for my CSV file (as I described above). But please don't worry. I will continue with my search for a solution for this. Thanks again.
-
What is the problem with cvp's solution? Does it still write the extra header row?
Your problem was that you were calling
writer.writeheader()
When you were appending. Presumably that is now solved... But is there another issue?
-
@JonB In his first post after my answer about external files, he describes two problems a first and a second...
And I'm not sure to understand the secondSecond: Even beter I want the CSV go to a horizontal presentation like:
-
I'll point out that you should delete the data.csv after implementing the changes, otherwise the old errors will still be there
-
@JonB I did it before each test, hoping he did the same
-
I think he actually wanted a ”transposed” layout.
@jokiehints said:
geb_dag, geb_mnd, geb_jr, vnaam, a_naam,
19, 10, 1981, 2, 5Which should be an easy change to @cvp’s code.
-
ahh, in that case, you cannot use append for the file mode, but instead must read the whole file in first, append the date, then write it out again. ..
-
@JonB yes but only if you change fields names, not if you add new records to existing variables.