Python - csv file is empty after using csv writer

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

提交回复
热议问题