【问题标题】:Write request content into CSV file python code将请求内容写入 CSV 文件 python 代码
【发布时间】:2021-08-15 22:50:19
【问题描述】:

我正在使用以下代码从仪表板获取数据作为 json 文件:

ursl='https://xxxxxxxxx'
parameter = {
"access_token": 'ABCD',
                "startDate":"2021-05-23",
                "endDate":"2021-05-25",
                "userId":'ERTI'
}
r = requests.get(url = ursl, params = parameter) 

然后我将内容保存为 json 文件,然后将其写入 CSV 文件:

data=r.content
datajson=r.json() 
# opening the csv file in 'w+' mode
file = open('DaTA.csv', 'w+')
  
# writing the data into the file
with file:    
    write = csv.writer(file)
    write.writerow(datajson)

但我只在一个单元格中获取所有数据。 这是数据的快照:

{'date': {'_when': '2021-05-25', '_date': '2021-05-25T00:00:00.000Z'}, 'timeInterval': '1min', 'userId': '96K7D9', 'id': '60ac1401211c48001774aa3b', 'activities-heart': [{'customHeartRateZones': [], 'dateTime': '2021-05-25', 'heartRateZones': [{'caloriesOut': 993.8944, 'max': 115, 'min': 30, 'minutes': 1067, 'name': 'Out of Range'}, {'caloriesOut': 0, 'max': 142, 'min': 115, 'minutes': 0, 'name': 'Fat Burn'}, {'caloriesOut': 0, 'max': 175, 'min': 142, 'minutes': 0, 'name': 'Cardio'}, {'caloriesOut': 0, 'max': 220, 'min': 175, 'minutes': 0, 'name': 'Peak'}], 'value': '65.31'}], 'activities-heart-intraday': 
{'dataset': [{'time': '00:45:00', 'value': 62}, {'time': '00:46:00', 'value': 61}, {'time': '00:47:00', 'value': 61}, {'time': '00:48:00', 'value': 59}, {'time': '00:49:00', 'value': 59}

您有什么建议吗,因为我希望数据是从数据集单词开始的两列时间和值。

【问题讨论】:

    标签: python json csv python-requests dashboard


    【解决方案1】:

    我不确定 csv 编写器是否允许您在不逐行循环的情况下执行您需要的操作。 也许改用pandas?

    import pandas as pd
    df = pd.DataFrame(datajson['activities-heart-intraday']['dataset'])
    df.to_csv("data.csv", index=False)
    

    【讨论】:

    • 谢谢,这很有效,我刚刚在 ['activities-heart-intraday'] 之前添加了 [0]。
    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多