【问题标题】:Why did my Python code get the IndexError: list index out of range为什么我的 Python 代码会出现 IndexError: list index out of range
【发布时间】:2019-12-06 06:57:17
【问题描述】:

当我运行代码时,我遇到了以下错误:

IndexError: 列表索引超出范围

我的代码有什么问题?

fin = open('words.txt')

for line in fin:
    word = line.strip()
    if len(word) > 20:
        print(word)

print(fin.readlines()[1])  #It is in this line that the error report shows

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您正在尝试获取执行readlines 方法结果的第二个元素(从零开始)。默认情况下它是不安全的,因为文件只能包含一个字符串。 但是在这种特殊情况下,您将在fin.readlines() 中收到空列表,无论打开文件中的行数如何,因为您已经阅读了上面的行(使用for line in fin 循环)。你不能只读两遍,需要寻找开头或重新打开文件:

~  echo 1 >> t.txt
~  echo 2 >> t.txt
~  echo 3 >> t.txt
~  python3

两次阅读内容:

>>> with open('t.txt') as f:
...   f.readlines()
...   f.readlines()
...
['1\n', '2\n', '3\n']
[]

寻求开始:

>>> with open('t.txt') as f:
...   f.readlines()
...   f.seek(0)
...   f.readlines()
...
['1\n', '2\n', '3\n']
0
['1\n', '2\n', '3\n']

【讨论】:

    【解决方案2】:

    这是因为循环后读取的文件已经结束。 使用seek,您可以再次将指针设置到开头。

    fin = open('text_file.txt')
    
    for line in fin:
        word = line.strip()
        if len(word) > 20:
            print(word)
    fin.seek(0, 0)
    print(fin.readlines()[1])
    

    这是一个链接https://python-reference.readthedocs.io/en/latest/docs/file/seek.html
    目前还不清楚你到底想做什么?但错误应该消失。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2015-02-11
      • 2016-04-21
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      相关资源
      最近更新 更多