从请求写入文件的Python循环

时间:2019-04-04 11:32:21

标签: python python-3.x python-requests

am试图编写一个通过请求从URL获取.json的循环,然后将.json写入.csv文件。然后我需要一遍又一遍,直到我的名字列表(.txt文件)完成(89行)。我不能让它遍历整个列表,它只会得到错误:

AttributeError: module 'response' has no attribute 'append'

我找不到问题,如果我将“响应”更改为“响应”,我也会收到错误消息

with open('listan-{}.csv'.format(pricelists), 'w') as outf:
OSError: [Errno 22] Invalid argument: "listan-['A..

我似乎找不到适合自己目的的循环。由于我是python的初学者,我希望我可以在这里获得一些帮助并了解更多信息。

到目前为止我的代码。

#Opens the file with pricelists

pricelists = []

with open('prislistor.txt', 'r') as f:
    for i, line in enumerate(f):
        pricelists.append(line.strip())

# build responses 
responses = [] 
for pricelist in pricelists: 
    response.append(requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers))

#Format each response 
fullData = [] 
for response in responses: 
    parsed = json.loads(response.text)
    listan=(json.dumps(parsed, indent=4, sort_keys=True))

    #Converts and creates a .csv file.
    fullData.append(parsed['Prices'])



with open('listan-{}.csv'.format(pricelists), 'w') as outf:
    dw.writeheader()
    for data in fullData: 
        dw = csv.DictWriter(outf, data[0].keys())

        for row in data:
            dw.writerow(row)

print ("The file list-{}.csv is created!".format(pricelists)) 

2 个答案:

答案 0 :(得分:0)

您可以在进行api调用的位置(也导入json库)进行以下更改吗?

import json
responses = [] 
for pricelist in pricelists: 
    response = requests.get('https://api.example.com/3/prices/sublist/{}/'.format(pricelist), headers=headers)
    response_json = json.loads(response.text)
    responses.append(response_json)

,下面的代码也应该处于循环中,循环遍历价目表中的商品

for pricelist in pricelists:
    with open('listan-{}.csv'.format(pricelists), 'w') as outf:
        dw.writeheader()
        for data in fullData: 
            dw = csv.DictWriter(outf, data[0].keys())

            for row in data:
                dw.writerow(row)

    print ("The file list-{}.csv is created!".format(pricelists)) 

答案 1 :(得分:0)

最后使它正常工作。我在论坛上创建的另一个问题得到了帮助。 @waynelpu

我犯的错误是不要将代码放入循环中。

这里的代码就像一个魅力。

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.se/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