
[英]How to import multiple csv stocks files in python and do statistics on them at the same time?
[英]How can I import multiple JSON files and dump them on the same CSV using Python?
URLs = ['https://cornershopapp.com/api/v2/stores?locality=+01020&country=MX',
'https://cornershopapp.com/api/v2/stores?locality=+01110&country=MX',
'https://cornershopapp.com/api/v2/stores?locality=+01210&country=MX']
我有這個端點列表(上面只是一個例子——真正的列表要大得多)。 我想將這些JSON文件和 append 的數據獲取到一個CSV 。
這是python3的一個例子
import csv, json, sys
import urllib.request
outputFile = open("test.csv", 'w') #load csv file
with urllib.request.urlopen("https://cornershopapp.com/api/v2/stores?locality=+01020&country=MX") as url:
data = json.loads(url.read().decode())
#print (data)
output = csv.writer(outputFile) #create a csv.write
output.writerow(data[0].keys()) # header row
for row in data:
output.writerow(row.values()) #values row
這些示例鏈接的數據結構是分層的,因此將其展平為 CSV 結構並非易事。 有很多方法可以做到這一點,但我認為這不是你可以在 stackoverflow 上快速回答的問題。 也許其他人知道我不知道的庫,但我建議閱讀“ 如何在非遞歸優雅 Python 中展平深度嵌套的 JSON 對象”。
此代碼段使用requests
庫,它實際上是 Python 庫,用於處理與 HTTP 相關的任何內容。
此腳本會將當前工作目錄中的 output.csv 的 URL 中的URLs
的output.csv
轉儲。
EDIT: as others have pointed out, if you'd like to unnest the JSON of these endpoints you'll need to do a bit more work and I'd recommend checking out pandas and the json_normalize function OR study up on recursion and implement your自己取消嵌套 function
import json
import csv
import requests
URLs = ['https://cornershopapp.com/api/v2/stores?locality=+01020&country=MX',
'https://cornershopapp.com/api/v2/stores?locality=+01110&country=MX',
'https://cornershopapp.com/api/v2/stores?locality=+01210&country=MX']
with open('output.csv', 'w') as url_file:
# create CSV writer object
url_writer = csv.writer(url_file, delimiter=',')
for u in URLs:
response = requests.get(u).text
json_response = json.loads(response)
url_writer.writerow(json_response)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.