【问题标题】:Python loop that writes files from requests with going trough a listPython循环,通过列表从请求中写入文件
【发布时间】: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


    【解决方案1】:

    Python 使用缩进(空格、制表符)来标记代码块,您需要将循环逻辑放在循环块内

    #Opens the file with pricelists
    
    with open('prislistor.txt', 'r') as f:
        for i, line in enumerate(f): # from here on, a looping code block start with 8 spaces
            pricelists = (line.strip())
            # Keeps the indents
            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))
    
        # codes here is outside the loop but still INSIDE the 'with' block, so you can still access f here
    
    # codes here leaves all blocks 
    

    【讨论】:

    • 像魅力一样工作。
    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多