if statment:“IndexError:list index out of range”

时间:2018-04-30 19:07:10

标签: python

您好,我有这段代码:

array = 0
with open('items.txt') as json_file:  
    data = json.load(json_file)
    abre_arquivo1 = open("dict.txt","w") 
    for p in data['data']:
        abre_arquivo1.write(str(p['order_id'])+ "\','")
        abre_arquivo1.write(str(p['pedido_venda'])+ "\','") 
        abre_arquivo1.write(str(p['supplier_id'])+ "\','") 
        abre_arquivo1.write(str(p['created_at'])+ "\','") 
        abre_arquivo1.write(str(p['data_retorno_nf'])+ '\n')
        for item in p:
            abre_arquivo1.write(str(p['items'][array]['item'])+ "\','")
            abre_arquivo1.write(str(p['items'][array]['mm_product_id'])+ "\','")
            abre_arquivo1.write(str(p['items'][array]['mm_product_id'])+ "\','")
            abre_arquivo1.write(str(p['items'][array]['description'])+ "\','")
            array += 1         
            if array >= int(p['items'][array]['item']):
                array = 0
            else:
                print(array)
                next  

当我尝试执行此错误时,此错误会在If语句中显示“列表索引超出范围”,而不是更改array = 0的值。 我在这里做错了什么?

items.txt文件内部是json:

{"data":[{"order_id":74415,"pedido_venda":"Z92211","supplier_id":1042,"status":9,"priority":null,"created_at":"2014-09-22 00:00:00","approved_at":"2014-09-19 00:00:00","assistence":0,"items":[{"item":"0002","mm_product_id":"98610","sku":"BA1068 BR","description":"Bau Art in Moveis BA1068 BR Branco                      ","quantity":1,"unity":"UN","price_unity":72.86,"price_total":72.86,"cst":null},{"item":"0003","mm_product_id":"98616","sku":"BL1030FR","description":"Balcao para Forno Microondas Art in Moveis BL1030 FR Fresno ","quantity":1,"unity":"UN","price_unity":86.11,"price_total":86.11,"cst":null},{"item":"0004","mm_product_id":"98629","sku":"AR4000 BR","description":"Armario para lavanderia Art in Moveis AR4000 BR Branco   ","quantity":1,"unity":"UN","price_unity":146.28,"price_total":146.28,"cst":null}],"data_retorno_nf":"2014-10-10","data_estimada_entrega_cd":"2014-10-15
00:00:00","prazo_para_faturamento":"2014-10-10","filial":[],"cliente":[{"bairro":" Jardim S\u00e3o Paulo(Zona Norte)","cep":"02040090","cidade":"S\u00e3o Paulo","cpfcnpj":"13549318820","email":"1042_artin@sandbox","endereco":"R Ag Gomes, 258, apto.92","ibge":"00000","ibgecompleto":"3500000","incricaoestadual":"ISENTO","nome":"SILVANA ANGELICA LOPES","telefone":"11- 36760352","tipocli":"F","tipocontrib":"F","uf":"SP"}],"transportadora":[]}

1 个答案:

答案 0 :(得分:0)

这里你不需要array循环索引变量。只需使用for item in p['items']:直接遍历列表即可。

这将显着简化此类代码,因为您不必编写所有容易出错的array += 1代码。

data = json.load('items.txt')['data']
with open('dict.txt', 'w') as fp:
    for p in data:
        fp.write("'{order_id}', '{pedido_venta}', '{supplier_id}'".format(**p))
        for item in p['items']:
            fp.write('{item}', '{mm_product_id}', '{description}'".format(**item))

根据需要调整格式字符串以获得预期的输出。

请注意,原始for item in p:会遍历对象p中的每个键,而不是遍历列表p['items']中的项目。