为什么读取文件时会出现 IndexError? [重复]

问题描述 投票:0回答:1

我正在尝试读取一个文件,获取它有多少行,并检查新行以查看它是否满足特定条件。

with open(path, "r") as g:
     readlen = len(g.readlines())
while True:
     with open(path, "r") as h:
          latest_line = fix_line(h.readlines()[readlen])

我很困惑,因为它在另一段代码中起作用。 (同上)

python file-handling
1个回答
1
投票

你的代码有几个问题。

首先,列表确实是从0开始索引的,所以需要减一(因为是从0开始计数的,列表中索引最高的就是长度减一)

所以,这确实打印了最后一行:

with open("./hello.txt") as f:
    length = len(f.readlines())

with open("./hello.txt") as g:
    last_line = g.readlines()[length-1]

print(last_line)

然而,在 python 中,有一种更简单的方法来获取列表的最后一个元素。您可以使用负索引环绕,因此,这也适用:

with open("./hello.txt") as g:
   last_line = g.readlines()[-1]

print(last_line)

但是,如果您打算做的不仅仅是阅读最后一行,我建议将文件累积到一个列表中。您已经清楚地注意到

readlines()
返回一个被消耗的迭代器,这就是您阅读它两次的原因。但是,更简洁的方法是将文件累积到列表中。

with open("./hello.txt") as g:
    file = list(g.readlines())

# Using your original method
last_line1 = file[len(file)-1]

# Using the negative indexes
last_line2 = file[-1]

print(last_line1, last_line2)

如果你的文件很大,你不能只读取整个文件,而你只需要读取最后一行,那么查看这个问题也会有所帮助: 如何在 Python 中读取文件的最后一行?

希望对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.