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
相关问题 更多 >
编程相关推荐