代码之家  ›  专栏  ›  技术社区  ›  small_python

csv。编写器:需要运行循环,但它会在一次迭代后停止

  •  0
  • small_python  · 技术社区  · 7 年前

    我试图从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()
    

    这样,程序将循环一次,写入 “文件.csv” 一次,然后关闭,出现以下错误:

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

    我尝试添加 with 在一些地方发表声明,但我什么都做不到。

    我怎样才能让它工作?

    1 回复  |  直到 7 年前
        1
  •  0
  •   toheedNiaz    7 年前

    您的代码看起来很好。你不需要 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