简体   繁体   English

csv.writer:需要运行循环,但在一次迭代后停止

[英]csv.writer: Need to run loop, but it stops after one iteration

I am attempting to pull from an API. 我正在尝试从API中提取。 The file runs fine if coded to run a single time. 如果编码为一次运行,则文件运行良好。 But I am having issues when coded to run once every minute ( x[5]==0 ). 但是我在编码为每分钟运行一次时遇到问题( x[5]==0 )。 The program does pull from the API (as evidenced by <print(i)> ), but doesn't seem to interact with the CSV file. 该程序确实从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"]])

The program will loop through and print , but it will not write to "file.csv" . 该程序将循环遍历并print ,但不会写入"file.csv" I attempted to get the CSV file to close . 我试图close CSV文件。

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

With this, the program will loop through once, write to "file.csv" once, then shut down with the following error: 这样,程序将循环遍历一次,一次写入"file.csv" ,然后因以下错误而关闭:

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

I tried adding a with statement in a few places, but I couldn't get anything to work. 我尝试在一些地方添加with语句,但是我什么都没用。

How can I get this to work? 我该如何工作?

your code looks fine. 您的代码看起来不错。 you don't need c.close() 你不需要c.close()

just add c.flush() at the end of your code . 只需在代码末尾添加c.flush() as you have infinite while loop you just need to flush data into you csv file. 因为您有无限的while循环,所以只需要将数据刷新到csv文件中即可。

hope this fixes your issue. 希望这能解决您的问题。

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

read this file.flush 阅读此文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM