0

I am attempting to pull from an 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). The program does pull from the API (as evidenced by <print(i)>), but doesn't seem to interact with the CSV file.

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". I attempted to get the CSV file to close.

      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:

    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.

How can I get this to work?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • You get that error because you close the file and don't reopen it. – user3483203 Mar 26 '18 at 19:33
  • Isn't c = open("file.csv", "a") supposed to make it re-open every time? – small_python Mar 26 '18 at 19:35
  • please use the answer from here when it comes to opening files [SO](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file) you can follow the same struction with using `with open()` – gyx-hh Mar 26 '18 at 19:44

1 Answers1

0

your code looks fine. you don't need c.close()

just add c.flush() at the end of your code . as you have infinite while loop you just need to flush data into you csv file.

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

toheedNiaz
  • 1,435
  • 1
  • 10
  • 14