skip to Main Content

I am trying to get a timeloop with which I can download the data every 5 seconds for 1 minute and save them in a csv file.

The data consists in an argument and its value and looks like this:

{
  "blood_pressure_diastolic_value": 70,
  "blood_pressure_systolic_value": 120,
  "heart_rate_value": 120,
  "respiratory_rate_value": null,
  "sat02_value": 95
}

I would like the header to be the names (e.g. blood_pressure_diastolic_value) and then for each timeframe input a new line with the given values.

import schedule
import requests
import json

def func():
    csv_file = open('cam_data.csv', 'wb')
    req = requests.get('URL')
    data = req.json()
    csv_file.write(data())
    csv_file.close()

schedule.every(5).seconds.do(func)

while True:
    schedule.run_pending()
    time.sleep(60)

This code just saves one entire output in the file.

2

Answers


  1. I think the problem here is u are using time.sleep(60) in your while loop.

    Also you are trying to write to the csv file which will edit the whole file.
    But you probably want to append to the csv file.

    Probably use this

        csv_file = open('cam_data.csv', 'a')
    

    If you want the scheduler to run every 5 seconds , use schedule.every(5)

    And if you want your while loop to stop after 1 minute , you can use this

    import time
    
    run_until = time.time() + 60 * 1
    while time.time() < run_until:
        # do whatever you do
    
    Login or Signup to reply.
  2. You override your file every time you run func.
    This means you will always end up with the last return of func. If you want the results of all runs you have to either change your file name every time you run the function or you open the file in append mode.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search