簡體   English   中英

如何從包含 url 文件的 json 文件下載 csv 文件到 Z628CB5675FF524F3E719B7AAE8883F 文件?

[英]How to download csv files from a json file which contains the url to the csv files?

我正在運行一個文件,該文件將包含 url 的 json 文件下載到多個 csv 文件中。 它看起來像那樣。

{"data_files":
{"i_p":["https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_i_p.1_0.1.csv.gz",
"https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_i_p.1_0.2.csv.gz"],
"c_p":["https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_c_p.1_0.1.csv.gz",
"https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_c_p.1_0.2.csv.gz"]},
"date":"2021-05-05"}

現在我想下載 json 文件中的所有文件。 我正在使用以下代碼。

import requests
from requests.auth import HTTPBasicAuth
import json
import urllib
import datetime

myResponse1 = requests.get('https://dashboard.s.com/api/1/user.json?api_key=xxxxxxxxx&personal_key=xxxxxxxx')

if(myResponse1.ok):
    file = open("V.json", "wb")
    file.write(myResponse1.content)
    file.close()
    
    
file = open('V.json', 'r')
id = 0
for line in file:
   response = urllib.request.urlretrieve(line, str(id) + '.csv')
   id+=1
    
else:
  # If response code is not ok (200), print the resulting http error code with description
    myResponse1.raise_for_status()

The above code is able to download the json file but I am not sure how to use the json file to download the csv files stored inside the json.Can someone tell me how can I do that?

不得不玩弄你的 json,但如果你能把它弄到迭代鍵/值對的地步,使用請求來下載文件

data = '''{"data_files":
{"i_p":["https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_i_p.1_0.1.csv.gz",
"https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_i_p.1_0.2.csv.gz"],
"c_p":["https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_c_p.1_0.1.csv.gz",
"https://dashboard.s.com/api/1/user/downloads/2021-05-05/all_2021-05-05_c_p.1_0.2.csv.gz"]},
"date":"2021-05-05"}'''

dataj = json.loads(data)

for k,v in dataj['data_files'].items():
    for f in v:
        print(f)
        r = requests.get(f, allow_redirects=True)
        print(f.split('/')[-1]) # split out the file name
        open(f.split('/')[-1], 'wb').write(r.content) # write the file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM