将restapi返回的响应转换为CSV

2024-05-15 00:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将restapi返回的响应写入csv文件。由于有多个请求,我正在逐个调用API。所以,会有多种反应。我无法达到所需的格式。在

所需格式:

name,job,id,createdAt
morpheus,leader,727,2018-10-12T12:04:39.234Z
Mark,SSE,925,2018-10-12T12:04:40.200Z
Taylor,SE,247,2018-10-12T12:04:41.115Z

代码:

^{pr2}$

Tags: 文件csvnameapirestapiid格式job
2条回答

假设您从服务器获取的数据与您要查找的密钥完全相同,则应该使用以下方法:

data = [] # Your data here.
url = 'https://reqres.in/api/users'

desired_columns = ['name', 'job', 'id', 'createdAt']
with open('response.csv', 'w') as f:

    # First we need to write the column names to the file
    f.write(','.join(desired_columns) + '\n')

    for element in data:
        r = requests.post(url, json=element)

        response = json.loads(r.text)

        # Here, I will assume response has 'name', 'job', 'id' and 'createdAt'
        # as keys to the dictionary. We will save them to the list 'data_to_write'
        # And then write that out the same way we did above.
        data_to_write = []
        for column in desired_columns:
            data_to_write.append(response[column])

        f.write(','.join(data_to_write) + '\n')

Python提供了对csv读写的内置支持,允许您用不同的分隔符和转义逻辑定义方言。在

包含分隔符、换行符或转义符的单元格值需要转义,或者生成的csv被破坏—csv模块会为您执行此操作。您可以选择不同的格式(excel在加载csv时可能会很挑剔),也可以定义自己的格式。在

https://docs.python.org/3/library/csv.html#csv.writer

相关问题 更多 >

    热门问题