【问题标题】:Have an index error I don't know how to correct有一个索引错误我不知道如何纠正
【发布时间】:2016-10-18 10:42:12
【问题描述】:

我在网站的其他地方找到了这段代码,但由于某种原因,我不断收到相同的错误消息:

products[row[0]] = [row[1], row[2], row[3]]
IndexError: list index out of range.

我不确定如何纠正这个问题,感谢任何帮助,谢谢。

这是代码:

MAX_FIELD_LEN = 8

def main():
    products = {}
    product_location  = {}
    location = 0
    # This is the file directory being made.
    with open('stockfile.txt', 'r+') as f:
        # This is my file being opened.

        for line in f:
            # keep track of each products location in file  to overwrite with New_Stock
            product_location[line.split(',')[0]] = location
            location += len(line)
            # Need to strip to eliminate end of line character
            line = line[:-1]
            # This gets rid of the character which shows and end of line '\n'
            row = line.split(',')
            # The row is split by the comma
            products[row[0]] = [row[1], row[2], row[3]]
            # The products are equal to row 1 and row 2 and row 3. The GTIN is going to take the values of the product and price so GTIN 12345678 is going to correspond to Fridge and 1.

        print(products)
        total = 0

        while True:
            GTIN = input('Please input GTIN: ')
            # To terminate user input, they just need to press ENTER
            if GTIN == "":
                break
            if (GTIN not in products):
                print('Sorry your code was invalid, try again:')
                break

            row = products[GTIN]
            description, value, stock = row
            print('Stock data: ')
            print('GTIN \t\tDesc. \t\tStock \t\tValue')
            print(GTIN,'\t',description,'\t', stock, '\t', value)

            quantity = input('Please also input your quantity required: ')
            row[2] = str(int(stock) - int(quantity))
            product_total = int(quantity) * int(value)
            for i in range(len(row)):  
                row[i]  = row[i].rjust(MAX_FIELD_LEN)
            New_Stock = GTIN.rjust(MAX_FIELD_LEN) + ',' + ','.join(row) + '\n'
            #print(New_Stock, len(New_Stock))
            f.seek(product_location[GTIN])
            f.write(New_Stock)
            print('You bought: {0} {1} \nCost: {2}'.format(GTIN, description, product_total))

            total = total + product_total
        f.close()
        print('Total of the order is £%s' % total)

main()

【问题讨论】:

  • 如果您只在问题中包含相关信息而不是整个代码,这将有所帮助。
  • 听起来您的文件中有没有 3 个或更多逗号的行。也许你有 empty 行?
  • 我的猜测是 stockfile.txt 确实包含少于 3 个 "," 字符的行。你也可以提供输入吗?
  • 尝试在循环开头添加if not line.strip(): continue...
  • 请打印此行的输出row = line.split(',')

标签: python indexoutofboundsexception


【解决方案1】:

请检查您的输入文件 'stockfile.txt',至少有一行文件没有 3 个或更多的“,”。或者您的数据之间有一些空白行。

【讨论】:

  • 是的,只是文件有问题,由于某种原因,一切都变了,但现在一切都好了,谢谢 :)
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 2012-04-16
  • 2016-06-23
  • 2021-09-11
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多