Writing csv files in python (Files are left blank at the end of the operation)

妖精的绣舞 提交于 2019-12-08 06:17:28

问题


I am writing to csv in python, and I was wondering why my output files are blank when the program completes running. First off, here is my code:

reader = csv.reader(open(location, 'rU'), delimiter = ',', quotechar = '"')
writer = csv.writer(open('temp.csv', 'wb'), delimiter = ',', quotechar = '"')

writer.writerow(["test", "test", "test", "test", "test", "test", "test"])

count = 0
for row in reader:
    if count != 0 and count < len(split):
        writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5], split[count-1]])
    count = count + 1

I know a few things about it:

  • When the program finishes, all that is written to 'temp.csv' is the "test" line. The rest of the document is empty.
  • If I force stop the program in the middle of running, there is in fact text being written to the file: it just gets wiped for some reason.
  • I've done some research, and lots of people have found that "closing" the csv file solves their problems, but that doesn't seem to work for me, unless I am missing something obvious!

Thanks in advance for your help!

Edit: here is some updated code I am working with:

infile = open(location, 'rU')
outfile = open('temp.csv', 'wb')
reader = csv.reader(infile, delimiter = ',', quotechar = '"')
writer = csv.writer(outfile, delimiter = ',', quotechar = '"')
split = email_text.split('NEW MESSAGE BEGINS HERE')

count = 0
for row in reader:
    if count != 0 and count < len(split):
        writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5], split[count-1]])
        outfile.flush()
    count = count + 1

infile.close()
outfile.close()

回答1:


You're not closing the file. While this may work fine if you're just reading a file, it's definitely not a good idea to do this when writing a file.

Use a context manager:

with open(location, 'rU') as infile, open('temp.csv', 'wb') as outfile:
    reader = csv.reader(infile, delimiter = ',', quotechar = '"')
    writer = csv.writer(outfile, delimiter = ',', quotechar = '"')
    ...

This ensures that the files will be closed when the with block is exited (even if it's because of an exception).




回答2:


Change the first two lines to save the opened file handles, and then include close invocations afterwards

reader_file = open(location, 'rU')
writer_file = open('temp.csv', 'wb')
reader = csv.reader(reader_file, delimiter = ',', quotechar = '"')
writer = csv.writer(writer_file, delimiter = ',', quotechar = '"')

# ... rest of code ...

reader_file.close()
writer_file.close()


来源:https://stackoverflow.com/questions/11454453/writing-csv-files-in-python-files-are-left-blank-at-the-end-of-the-operation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!