#python #indexoutofboundsexception
#python #исключение indexoutofboundsexception
Вопрос:
Я нашел этот код в другом месте на сайте, но по какой-то причине я продолжаю получать одно и то же сообщение об ошибке:
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 ttDesc. ttStock ttValue')
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()
Комментарии:
1. Было бы полезно, если бы вы включили только соответствующую информацию в свой вопрос вместо всего кода.
2. Похоже, у вас в файле есть строки, в которых нет 3 или более запятых. Возможно, у вас есть пустые строки?
3. Я предполагаю, что stockfile.txt содержит строку, содержащую менее 3 символов «,». Не могли бы вы также предоставить входные данные?
4. Попробуйте добавить
if not line.strip(): continue
в начале цикла…5. Пожалуйста, выведите вывод этой строки
row = line.split(',')
Ответ №1:
Пожалуйста, проверьте свой входной файл ‘stockfile.txt ‘, по крайней мере, в одной строке вашего файла нет 3 или более «,». Или у вас есть несколько пустых строк между вашими данными.
Комментарии:
1. Да, просто проблема с файлом, по какой-то причине все изменилось, но теперь все хорошо, спасибо 🙂