我正在写python中的csv,我想知道为什么程序运行完毕后我的输出文件是空白的。首先,这是我的代码:
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
我知道一些事情:
提前感谢您的帮助!
编辑:这是我正在使用的一些更新代码:
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()
答案 0 :(得分:5)
您没有关闭该文件。虽然如果您只是阅读文件,这可能会正常工作,但在编写文件时执行此操作绝对不是一个好主意。
使用上下文管理器:
with open(location, 'rU') as infile, open('temp.csv', 'wb') as outfile:
reader = csv.reader(infile, delimiter = ',', quotechar = '"')
writer = csv.writer(outfile, delimiter = ',', quotechar = '"')
...
这可以确保在退出with
块时关闭文件(即使是因为异常)。
答案 1 :(得分:1)
更改前两行以保存打开的文件句柄,然后再包括关闭调用
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()