2016-10-18 105 views
0

我發現這個代碼在網站上其他地方,但由於某種原因,我不斷收到同樣的錯誤信息:有一個索引錯誤,我不知道怎麼糾正

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() 
+0

如果您只在問題中包含相關信息而不是整個代碼,這將有所幫助。 –

+5

聽起來像您的文件中沒有3個或更多逗號的行。也許你有*空*行? –

+1

我的猜測是stockfile.txt包含少於3個「,」字符的行。你能提供輸入嗎? – Binus

回答

0

請檢查您輸入文件「stockfile.txt」,您的文件中至少有一行沒有3個以上「」。或者你的數據之間有一些空行。

+0

是啊只是一個問題該文件,由於某種原因,它都改變了,但它的一切都很好,謝謝:) –

相關問題