【问题标题】:Writing csv files in python (Files are left blank at the end of the operation)在python中编写csv文件(文件在操作结束时留空)
【发布时间】:2023-04-09 05:27:02
【问题描述】:

我正在用 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”的所有内容都是“测试”行。文档的其余部分为空。
  • 如果我在运行过程中强制停止程序,实际上会向文件写入文本:它只是由于某种原因而被擦除。
  • 我做了一些研究,很多人发现“关闭” 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()

【问题讨论】:

  • 如何关闭文件?您没有保存可以使用 .close() 方法的文件句柄。
  • 旁白:您可以使用for count, row in enumerate(reader):,而不是手动增加计数。
  • @brian:我刚刚有了一个疯狂的想法。您能否在循环中添加 print count 语句并确认计数实际上在增加?

标签: python csv writer


【解决方案1】:

您没有关闭文件。虽然如果您只是在读取文件,这可能会很好,但在写入文件时这样做绝对不是一个好主意。

使用上下文管理器:

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 块时关闭文件(即使是因为异常)。

【讨论】:

  • 嗨,我试过了,但在“with open(location, 'rU')”位出现“无效语法”错误。抱歉,我是 python 新手!
  • @brian:您必须使用旧版本的 Python。 with 自 Python 2.6 起可用(如果您以 from __future__ import with_statement 开始脚本,则在 Python 2.5 上可用)。
  • 我使用的是 python 2.4.3,但我在网络上,所以我没有安装或更新任何东西的权限。有什么方法可以在 2.4.3 中阅读这些内容吗?
  • 哇。 Python 2.4 又有多少年了?超过6年?好的,那么没有with 声明给你。但是你仍然可以调用infile = open(...)outfile = open(...),然后调用reader = csv.reader(infile,...) 等,最后调用infile.close(),尤其是outfile.close()
  • 好的,我这样做了,但它仍然没有在我的文件中留下任何东西!我不确定是什么问题...
【解决方案2】:

更改前两行以保存打开的文件句柄,然后包含关闭调用

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

【讨论】:

  • 这对我不起作用,我的文件仍然是空的!
  • 您的 if 语句可能有问题。否则,您是否打算以二进制模式打开 writer_file?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 2011-06-27
  • 2010-12-13
相关资源
最近更新 更多