I wrote a code with which I can call data from url every 5 secodns and save it in a csv file:
import time
run_time = 30
run_until = time.time() run_time
while time.time() < run_until:
url = 'http://xxx'
csv_file = open('cam_data2.csv', 'a')
req = requests.get(url)
data = req.json()
csv_file.write(str(data)) #here I have to concade the value to str
csv_file.write('\n')
time.sleep(5)
csv_file.close()
Now my problem is that I am working with this tipe of data: {"blood_pressure_diastolic_value":70.0,"blood_pressure_systolic_value":120.0}
and the csv_file.write() method only allows me to save it as a string. Is there any other way that the json structure stays as it is so that I can later recall the value of each item?
CodePudding user response:
Although i would suggest to save it as json file instead of csv. But,if you still want to write to csv you can follow.
import time
import json
run_time = 30
run_until = time.time() run_time
while time.time() < run_until:
url = 'http://xxx'
csv_file = open('cam_data2.csv', 'a')
req = requests.get(url)
data = req.json()
# dumps the data using json library
csv_file.write(json.dumps(data))
csv_file.write('\n')
time.sleep(5)
csv_file.close()