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()
解决方案
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).