调用url并在每个x时间段后将数据保存到csv文件中

tpgth1q7  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(116)
run_time = 60
run_until = time.time() + run_time
while time.time() < run_until:
    if run_time % 5 == 0:
        url = 'URL'
        csv_file = open('cam_data1.csv', 'a')
        req = requests.get(url)
        data = req.json()
        csv_file.write(str(data))
        csv_file.close()

这是我写的代码,它每5秒调用一次url并将输出数据保存到csv文件中,output-data是一个json,看起来像这样:
{“血压舒张值”:70.0,“血压收缩值”:120.0,“心率值”:120.0,“呼吸率值”:55.0,“饱和度02_值”:95.0分
我不得不将这些值与另一个数据集进行比较,问题是代码将所有数据放在一个单元格中,这使得处理起来很困难,因为跟踪每个数据的时间戳很复杂。
我希望每个新的输出都存储在一个新的行中,每个参数都有自己的列,所以每个输出都有5列和一个新的行。
有谁能帮我一下,或者告诉我一种访问现有数据的替代方法?

3bygqnnd

3bygqnnd1#

解决方案如下:

import time

wait_seconds = 60
while True:
    url = 'URL'
    csv_file = open('cam_data1.csv', 'a')
    req = requests.get(url)
    data = req.json()
    csv_file.write(str(data))
    csv_file.close()
    time.sleep(wait_seconds)
niwlg2el

niwlg2el2#

一个很好的方法是':

import time

wait_seconds = 60
while True:
    url = 'URL'

    # context manager close the file automatically
    with open('cam_data1.csv', 'a') as csv_file:
        req = requests. Get(url)
        data = req.json()  # this returns a dictionary
        # we only take value of the dict not the key (title of your columns)
        for value in data.value():
           csv_file.write(f"{value};")  
           # IMPORTANT if you want 'classic' CSV replace the semi-colon by a coma
        csv_file.write("\n")  # This create a new line

相关问题