Python - csv file is empty after using csv writer

后端 未结 5 976
终归单人心
终归单人心 2021-01-12 22:19

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

相关标签:
5条回答
  • 2021-01-12 22:40

    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

    0 讨论(0)
  • 2021-01-12 22:42

    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.

    0 讨论(0)
  • 2021-01-12 22:50

    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?)

    0 讨论(0)
  • 2021-01-12 22:58

    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.

    0 讨论(0)
  • 2021-01-12 23:03

    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.

    0 讨论(0)
提交回复
热议问题