Python - csv file is empty after using csv writer

后端 未结 5 987
终归单人心
终归单人心 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

提交回复
热议问题