简体   繁体   English

在 while 循环中附加带有 API 数据的 CSV 文件

[英]Appending CSV file with API data in a while loop

I'm trying to use a with statement to write and append a CSV file.我正在尝试使用with语句来编写和附加 CSV 文件。 The with is being used in conjunction with a while loop that reads data and headers from a paginated API. with与从分页 API 读取数据和标头的while循环结合使用。

As you might see, I haven't worked out how to incorporate the with and while to achieve this.如您所见,我还没有想出如何将withwhile结合起来来实现这一点。

I'm using a defined function to return the data.我正在使用定义的函数来返回数据。 The API uses OAuth2. API 使用 OAuth2。 My account has multiple locations to download from (hence the location_id col):我的帐户有多个位置可供下载(因此是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

As you will notice, fetch_data_for_location() returns two items: data and response_headers .您会注意到, fetch_data_for_location()返回两项: dataresponse_headers

Next, I generate the response_headers for my chosen location by specifying [1] after the function.接下来,我通过在函数后指定[1]为我选择的位置生成response_headers

The while loop checks the headers ( data_headers ) for the header 'next-page' and continues to read the data until there is no header called 'next-page' . while循环检查标题 ( data_headers ) 中是否有标题'next-page'并继续读取数据,直到没有名为'next-page'标题。

Right now I've just set it up so the data will print when they are found.现在我刚刚进行了设置,以便在找到数据时打印数据。

#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]

I would like to append a CSV file with data from this while loop.我想用这个while循环中的数据附加一个 CSV 文件。 I thought something like this would work:我认为这样的事情会起作用:

with open('results.csv', 'w') as csvfile:

But, I don't know how to reference that in my while loop.但是,我不知道如何在我的while循环中引用它。

The last thing I should mention is that the data are a dict object and have a format like this:我应该提到的最后一件事是数据是一个dict对象,并且具有如下格式:

{'locationId': 6544992693911552, 'parameters': 
[{'parameterId': 'Pressure', 'unitId': 'Unspecified', 'customParameter': True, 'readings': 
[{'timestamp': 1627044780, 'value': 0.09}, {'timestamp': 1627044840, 'value': 0.09}

The timestamps continue like that until the next parameter.时间戳会继续这样,直到下一个参数。

Without knowing how your response.json() looks like, this is just an example:在不知道您的 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)

To write/append data to CSV file assuming print(fetch_data_for_location(oauth, location1, page=data_headers["next-page"], start_time=0, end_time=None)[0]) is what you want to write into a CSV file, try below要将数据写入/附加到 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]

The w+ is key here as it appends data if the file already exists, otherwise creates it. w+是这里的关键,因为如果文件已经存在,它会附加数据,否则会创建它。 You can read more here你可以在这里阅读更多

You can use python's unpacking feature to avoid any additional call to fetch data.您可以使用 python 的解包功能来避免任何额外的获取数据的调用。 Something like below to fetch data and headers in one go.像下面这样一次性获取dataheaders

data, headers = fetch_data_for_location(oauth, location1, start_time=0, end_time=1653645628)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM