在python中编写csv文件(文件在操作结束时留空)

时间:2012-07-12 14:47:53

标签: python csv writer

我正在写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

我知道一些事情:

  • 当程序完成时,写入'temp.csv'的所有内容都是“test”行。文件的其余部分是空的。
  • 如果我在运行过程中强制停止程序,实际上文本正在写入文件:它只是因某种原因被擦除。
  • 我做了一些研究,很多人发现“关闭”csv文件解决了他们的问题,但这对我来说似乎没有用,除非我遗漏了一些明显的东西!

提前感谢您的帮助!

编辑:这是我正在使用的一些更新代码:

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()

2 个答案:

答案 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()