Python - csv file is empty after using csv writer

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


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.

Tags:

Python

Csv