【问题标题】:csv.writer: Need to run loop, but it stops after one iterationcsv.writer:需要运行循环,但在一次迭代后停止
【发布时间】:2018-03-26 19:29:38
【问题描述】:

我正在尝试从 API 中提取。如果编码为运行一次,该文件运行良好。但是当编码为每分钟运行一次时我遇到了问题(x[5]==0)。该程序确实从 API 中提取(<print(i)> 证明了这一点),但似乎不与 CSV 文件交互。

import csv
import time

c = open("file.csv", "a")
w = csv.writer(c, lineterminator="\n")

while True:
  x = time.localtime()
    if x[5]==0:

      client.request(r)
      print(i)
      for i in r.response["list"]
      w.writerow([i["list_item1"], i["list_item2"]])

程序将循环遍历print,但不会写入"file.csv"。我试图将 CSV 文件发送到 close

      client.request(r)
      print(i)
      for i in r.response["list"]
      w.writerow([i["list_item1"], i["list_item2"]])
      c.close()

这样,程序将循环一次,写入一次"file.csv",然后关闭并出现以下错误:

    w.writerow([i["list_item1"], i["list_item2"]])
ValueError: I/O operation on closed file.

我尝试在几个地方添加with 语句,但我无法正常工作。

我怎样才能让它工作?

【问题讨论】:

  • 您收到该错误是因为您关闭了文件并且没有重新打开它。
  • 不是 c = open("file.csv", "a") 应该让它每次都重新打开吗?
  • 在打开文件时请使用此处的答案SO,您可以按照相同的说明使用with open()

标签: python loops csv time


【解决方案1】:

您的代码看起来不错。你不需要c.close()

只需在代码末尾添加c.flush() 即可。 因为你有无限的while循环,你只需要将数据刷新到你的csv文件中。

希望这能解决您的问题。

 Note flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior. 

阅读此file.flush

【讨论】:

  • 宾果游戏!谢谢!
  • 它在没有 os.fsync() 的情况下工作,但我会添加它以更好地衡量。
猜你喜欢
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2016-08-18
  • 1970-01-01
  • 2019-11-16
  • 2021-07-28
相关资源
最近更新 更多