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
I'm not too familiar with the csv
module, but this does look like a file IO problem more than a csv
problem.
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:
spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ', quotechar='|')
Do this instead:
f = open('eggs.csv', 'w')
spamWriter = csv.writer(f, delimiter=' ', quotechar='|')
# the rest of your code
f.close()
Now you should see what you want in eggs.csv
Hope this helps
I tried this out in the python interpreter. In the first bit of code, I see content in the csv only after I exit python (when the file is closed). Definitely, this was something to with closing the file.
The code you posted works perfectly for me.
Are you sure that the directory in which you run that script is actually the directory you're checking? (Do you delete "eggs.gsv" every time before you try it?)
This is a bit late to the party, but a solution I have yet to see outside of a single comment is using with
and as
. In this case, it may look like:
import csv
with csv.writer(open('eggs.csv', 'w'), delimiter=' ', quotechar='|') as spamWriter:
spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
I've used this in the past with no problems.
That code works. Are you sure your OS isn't just rounding down the CSV size -- after all, it will only be a few bytes!
You can try print(open("eggs.csv").read())
to see whether the file is actually empty, or else more eggs.csv
from the command line.