【发布时间】:2015-09-19 12:07:16
【问题描述】:
我是编程新手,并且正在尝试使用 Python 3。我发现了一些处理 IndexError 的主题,但似乎对这种特定情况没有帮助。
我编写了一个函数,它打开一个文本文件,一次读取一行,然后将该行分割成单独的字符串,每个字符串都附加到一个特定的列表(记录行中的每个“列”一个列表) )。大多数切片是多个字符 [x:y],但有些是单个字符 [x]。
我收到了IndexError: string index out of range 消息,但据我所知,它不是。这是函数:
def read_recipe_file():
recipe_id = []
recipe_book = []
recipe_name = []
recipe_page = []
ingred_1 = []
ingred_1_qty = []
ingred_2 = []
ingred_2_qty = []
ingred_3 = []
ingred_3_qty = []
f = open('recipe-file.txt', 'r') # open the file
for line in f:
# slice out each component of the record line and store it in the appropriate list
recipe_id.append(line[0:3])
recipe_name.append(line[3:23])
recipe_book.append(line[23:43])
recipe_page.append(line[43:46])
ingred_1.append(line[46])
ingred_1_qty.append(line[47:50])
ingred_2.append(line[50])
ingred_2_qty.append(line[51:54])
ingred_3.append(line[54])
ingred_3_qty.append(line[55:])
f.close()
return recipe_id, recipe_name, recipe_book, recipe_page, ingred_1, ingred_1_qty, ingred_2, ingred_2_qty, ingred_3, \
ingred_3_qty
这是回溯:
Traceback (most recent call last):
File "recipe-test.py", line 84, in <module>
recipe_id, recipe_book, recipe_name, recipe_page, ingred_1, ingred_1_qty, ingred_2, ingred_2_qty, ingred_3, ingred_3_qty = read_recipe_file()
File "recipe-test.py", line 27, in read_recipe_file
ingred_1.append(line[46])
调用相关函数的代码是:
print('To show list of recipes: 1')
print('To add a recipe: 2')
user_choice = input()
recipe_id, recipe_book, recipe_name, recipe_page, ingred_1, ingred_1_qty, ingred_2, ingred_2_qty, \
ingred_3, ingred_3_qty = read_recipe_file()
if int(user_choice) == 1:
print_recipe_table(recipe_id, recipe_book, recipe_name, recipe_page, ingred_1, ingred_1_qty,
ingred_2, ingred_2_qty, ingred_3, ingred_3_qty)
elif int(user_choice) == 2:
#code to add recipe
失败的路线是这样的:
ingred_1.append(line[46])
我尝试读取的文本文件的每一行都有超过 46 个字符,所以我不明白为什么会出现越界错误(示例行如下)。如果我将代码更改为:
ingred_1.append(line[46:])
要读取切片而不是特定字符,该行会正确执行,而程序会在该行上失败:
ingred_2.append(line[50])
这让我认为它在某种程度上与从字符串中附加单个字符有关,而不是多个字符的切片。
这是我正在阅读的文本文件中的示例行:
001Cheese on Toast Meals For Two 012120038005002
我可能应该补充一点,我很清楚这不是很好的代码 - 通常有很多方法可以改进程序,但据我所知,代码应该可以实际工作。
【问题讨论】:
-
有空行吗?这将导致此错误。
-
输入文件中有标签吗?尝试打印行长。
-
我认为 unutbu 做到了——源文本文件的末尾有一个额外的换行符。删除它会发现附加代码中的另一个错误(忘记了某些列表名称末尾的 [i]) - 但是当我修复它时,一切都按预期工作。 :)
-
line[100000:]始终是合法的,无论行长如何。您可能需要添加一个tryexcept块并在异常时打印len(line)。 -
@RichCairns:很高兴你解决了这个问题。随意接受已经发布的答案之一。