[英]Appending CSV file with API data in a while loop
我正在尝试使用with
语句来编写和附加 CSV 文件。 with
与从分页 API 读取数据和标头的while
循环结合使用。
如您所见,我还没有想出如何将with
和while
结合起来来实现这一点。
我正在使用定义的函数来返回数据。 API 使用 OAuth2。 我的帐户有多个位置可供下载(因此是location_id
col):
def fetch_data_for_location(oauth_session, location_id, page=None, start_time=None, end_time=None):
# get data from first location returned
dataurl = "my url that I can't share"
params = {}
headers = {}
# Page is added to the header of the request
if page is not None:
headers['start-page'] = page
# Time filters are added to the query parameters of the request
if start_time is not None:
params['start-time'] = start_time
if end_time is not None:
params['end-time'] = end_time
response = oauth_session.get(dataurl, params=params, headers=headers)
data = response.json()
response_headers = response.headers
return data, response_headers
您会注意到, fetch_data_for_location()
返回两项: data
和response_headers
。
接下来,我通过在函数后指定[1]
为我选择的位置生成response_headers
。
while
循环检查标题 ( data_headers
) 中是否有标题'next-page'
并继续读取数据,直到没有名为'next-page'
标题。
现在我刚刚进行了设置,以便在找到数据时打印数据。
#get response headers
data_headers = fetch_data_for_location(oauth, location1, start_time=0, end_time=None)[1]
#get all data and write to csv
while data_headers["next-page"] is not None:
print(fetch_data_for_location(oauth, location1, page=data_headers["next-page"], start_time=0, end_time=None)[0])
data_headers = fetch_data_for_location(oauth, location1, page=data_headers["next-page"], start_time=0, end_time=None)[1]
我想用这个while
循环中的数据附加一个 CSV 文件。 我认为这样的事情会起作用:
with open('results.csv', 'w') as csvfile:
但是,我不知道如何在我的while
循环中引用它。
我应该提到的最后一件事是数据是一个dict
对象,并且具有如下格式:
{'locationId': 6544992693911552, 'parameters':
[{'parameterId': 'Pressure', 'unitId': 'Unspecified', 'customParameter': True, 'readings':
[{'timestamp': 1627044780, 'value': 0.09}, {'timestamp': 1627044840, 'value': 0.09}
时间戳会继续这样,直到下一个参数。
在不知道您的 response.json() 的情况下,这只是一个示例:
#get response headers
data, response_headers = fetch_data_for_location(oauth, location1, start_time=0, end_time=1653645628)
#get all data and write to csv
with open('results.csv', 'w') as csvfile:
while response_headers["next-page"] is not None:
csvfile.write(f"{data['value1']},{data['value2']}")
data, response_headers = fetch_data_for_location(oauth, location1, page=response_headers["next-page"], start_time=0, end_time=None)
要将数据写入/附加到 CSV 文件,假设print(fetch_data_for_location(oauth, location1, page=data_headers["next-page"], start_time=0, end_time=None)[0])
是您要写入 CSV 文件的内容, 试试下面
#get response headers
data_headers = fetch_data_for_location(oauth, location1, start_time=0, end_time=None)[1]
#get all data and write to csv
while data_headers["next-page"] is not None:
with open('results.csv', 'w+', encoding='UTF8') as csvfile:
#assuming data_to_write is going to be a dict and key1, key2 are one of the keys
data_to_write = fetch_data_for_location(oauth, location1, page=data_headers["next-page"], start_time=0, end_time=None)[0]
csvfile.write(f'{data_to_write["key1"]},{data_to_write["key2"]}')
data_headers = fetch_data_for_location(oauth, location1, page=data_headers["next-page"], start_time=0, end_time=None)[1]
w+
是这里的关键,因为如果文件已经存在,它会附加数据,否则会创建它。 你可以在这里阅读更多
您可以使用 python 的解包功能来避免任何额外的获取数据的调用。 像下面这样一次性获取data
和headers
。
data, headers = fetch_data_for_location(oauth, location1, start_time=0, end_time=1653645628)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.