Search code examples
pythonapicsvexportrefresh

How to refresh a csv export in Python every second?


I have this code for python that looks up an API key and writes into a file the findings. How can I make this refresh the contents of the file every one second?

import requests
import csv

r = requests.get('https://api.kraken.com/0/public/Trades?pair=XBTUSD').json()

c = csv.writer(open("order_book", "w"), lineterminator='\n')

for item in r['result']['XXBTZUSD']:
    c.writerow(item)

Solution

  • Schedule (https://pypi.python.org/pypi/schedule) seemed to be what you need.

    You will have to install their Python library:

    pip install schedule
    

    then modify the sample script :

    import schedule
    import time
    
    def job():
    
    schedule.every(1).seconds.do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    With your own function in job() and use the needed call for your timing.

    Then you can run it with nohup.

    Be advised that yu will need to start it again if you reboot.

    here is the docs