【问题标题】:How to download csv files from a json file which contains the url to the csv files?如何从包含 csv 文件 url 的 json 文件中下载 csv 文件?
【发布时间】:2021-05-05 16:31:58
【问题描述】:

我正在运行一个文件,该文件下载一个包含多个 csv 文件的 url 的 json 文件。它看起来像那样。

{"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()

上面的代码可以下载json文件,但是我不知道如何使用json文件来下载存储在json中的csv文件。有人可以告诉我该怎么做吗?

【问题讨论】:

  • json 缺少括号,请提供有效的 json 示例。

标签: python json csv urllib


【解决方案1】:

不得不玩弄你的 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

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多