Python file - csv is empty after using csv writer

Python newbie here. I tried to fix the problem of writing the csv file in a larger program and decided to go back to the basics to try and find the problem.

I wrote a sample code from the Python csv read and write documentation:

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, as reported as "0 kb". The same thing happened in my larger program (empty csv files). Am I missing something completely obvious?

Thanks!

EDIT :
I just tried changing the code:

 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 it worked. I am not sure why the first does not work for me.

+4
source share
4 answers

I am not very familiar with the csv module, but this seems like a problem with the IO file more than a csv problem.

The reason you don't see anything in the file is because python still has an open file. You need to close it.

So instead:

 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

+6
source

This code works. Are you sure that your OS does not just round the CSV size - in the end, it will be just a few bytes!

You can try print(open("eggs.csv").read()) see if the file is really empty, or more eggs.csv from the command line.

0
source

The code you posted works great for me.

Are you sure that the directory in which you run this script is actually the directory that you are checking? (Do you delete "eggs.gsv" every time before trying?)

0
source

I tried this in a python interpreter. In the first bit of code, I see the contents in csv only after exiting python (when the file is closed). Definitely it was something with closing the file.

0
source

All Articles