Python newbie here. I was trying to troubleshoot an issue with writing a csv file in a larger program and decided to go back to basics to try to find the problem.
I ran an exact code example from the Python csv reading and writing documention:
import csv
spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ', quotechar='|')
spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
When I go to my working directory and click on “eggs.csv” the file is empty is reported as being “0 kb”. This same thing was happening in my larger program (empty csv files). Am I missing something completely obvious?
Thank you!
EDIT:
I just tried modified the code to:
import csv
csvOut=open("eggs.csv", "wb")
spamWriter = csv.writer(csvOut, delimiter=' ', quotechar='|')
spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
csvOut.close()
And this worked. I am not sure why the first doesn’t work for me.
I’m not too familiar with the
csvmodule, but this does look like a file IO problem more than acsvproblem.The reason that you see nothing in the file is that python still has the file open. You need to close it.
So rather than doing this:
Do this instead:
Now you should see what you want in eggs.csv
Hope this helps