首页 > 解决方案 > 错误原因不明 - IndexError:列表索引超出范围

问题描述

我目前正在尝试编写一个 Python 脚本,该脚本允许我通过使用文本文件中的姓氏列表来创建用户名。

我有一个包含 100 个姓氏的文本文件,每个名字都在一个单独的行中:

Gibbs
Dorsey
Delgado
Spears
Hull
King
Bailey
Wilcox
Meza
Barber
Greer
Bradley
Cannon
Boyle
Lawrence
Marks
Shelton
Hess
Anderson
Snow
Hale
Russo
Schmitt
Burch
Deleon
Terrell
Carr
Lamb
Sanford
West
Pruitt
Everett
Gardner
Graves
Rollins
Jarvis
Banks
Wagner
Pugh
Nguyen
Thompson
Bullock
Erickson
Cortez
Lambert
Zavala
Harmon
Mcdowell
Randolph
Nichols
Mcknight
Haley
Leach
Weaver
Nolan
Rocha
Walton
Reeves
Gill
Valentine
Lucero
Le
Hinton
Choi
Cowan
Robles
Reilly
Strong
Adams
Braun
Cooper
Padilla
Chaney
Heath
Saunders
Ramos
Blackwell
Blake
Mathews
Sherman
Byrd
Bauer
Bell
Sims
Berg
Austin
Watkins
Donovan
Huang
Cabrera
Giles
Cherry
Petersen
Massey
Farrell
Knox
Archer
Black
Stevens
Santos

对于每个姓氏,我希望脚本将其附加到列表/数组中。

这是我的脚本:

file = open(r"E:\Users\User\Documents\Python\Username Creator\Surnames.txt", "r")

# Counts the amount of lines in the script and assigns them to a variable
line_count = 0
for line in file:
    if line != "\n":
        line_count = line_count + 1
file.close()

file2 = open(r"E:\Users\User\Documents\Python\Username Creator\Surnames.txt", "r")

# For each line of the text file, the script should assign the surname to a list called 'info'
info = []
x = -1
for i in range(line_count):
    x = x + 1
    fileRead = file2.readlines()
    info.append(fileRead[x])

但是,当我运行脚本时,我收到以下错误消息:

Traceback (most recent call last):
  File "E:\Users\User\Documents\Python\Username Creator\Username Creator.py", line 17, in <module>
    info.append(fileRead[x])
IndexError: list index out of range

我以前遇到过这个错误,但是这一次,我不知道我在脚本中写了什么会导致它显示这个错误。

有没有人知道我该如何解决这个错误?

标签: pythonlistloopsfile-handlingindex-error

解决方案


这是将文件中的项目放入列表的一种有点复杂的方式。它可以像这样简单得多:

info = []
with open('file.txt') as f:
    info = [x.rstrip() for x in f] 

为了完整起见,并回答你原来的问题,错误是因为你readlines()在循环内调用而产生的。第一次迭代将返回所有行,其他所有调用将返回一个空列表;因此,您不能错误地对其进行索引。


推荐阅读