Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - csv file is empty after using csv writer

Tags:

python

csv

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.

like image 266
Mina Avatar asked Oct 09 '10 15:10

Mina


1 Answers

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

like image 78
inspectorG4dget Avatar answered Sep 26 '22 02:09

inspectorG4dget