【发布时间】:2019-04-06 10:56:05
【问题描述】:
我正在尝试编写一个循环,通过请求从 url 获取 .json,然后将 .json 写入 .csv 文件。然后我一遍又一遍地需要它,直到我的名称列表(.txt 文件)完成(89 行)。我无法让它遍历列表,它只是选择我列表的底部名称然后退出。我需要它通过并基本上创建 89 个文件,并带有正确的 url。其他功能正常,但只执行一次。
我似乎找不到适合我的目的的循环。由于我是python的初学者,我希望我能在这里得到一些帮助并了解更多
我的代码
#Opens the file with pricelists
with open('prislistor.txt', 'r') as f:
for i, line in enumerate(f):
pricelists = (line.strip())
response = requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelists), headers=headers)
#Formats it
parsed = json.loads(response.text)
listan=(json.dumps(parsed, indent=4, sort_keys=True))
#Converts and creates a .csv file.
data = parsed['Prices']
with open('listan-{}.csv'.format(pricelists), 'w') as outf:
dw = csv.DictWriter(outf, data[0].keys())
dw.writeheader()
for row in data:
dw.writerow(row)
print ("The file list-{}.csv is created!".format(pricelists))
【问题讨论】:
标签: python python-3.x loops request