简体   繁体   English

索引超出范围,无法在Python中进行简单的“ readlines”操作

[英]Index out of range for simple `readlines` operation in Python

Basically I am trying to read the last few lines. 基本上,我正在尝试阅读最后几行。 I am baffled what leads to this error: 我很困惑导致此错误的原因:

nrows = 10
with open(filename, "r") as f:
    for ii in xrange(-nrows, 0, 1):
        last_line = f.readlines()[ii].strip().split(",")

When I tried it in the IDE, it has no problem when I use mere numbers, like this: 当我在IDE中尝试使用纯数字时,它没有问题,如下所示:

with open(filename, "r") as f:
    last_line = f.readlines()[-10].strip().split(",")

Somehow it looks like the xrange generated indices cannot be "used". 看起来xrange生成的索引似乎无法“使用”。 Is there a way around this? 有没有解决的办法?

Thank you very much for your attention and time! 非常感谢您的关注和时间!

The reason it works in your second example is because you call readlines() only once. 它在第二个示例中起作用的原因是因为您仅调用一次readlines()。

you can read file only once, so once you read all lines the file iterator points at EOF and returns empty list which will fail your [ii] attempt. 您只能读取一次文件,因此一旦读取了所有行,文件迭代器将指向EOF并返回空列表,这将使您的[ii]尝试失败。

To read file more than once you would have to call file.seek(0) after each round to move the iterator to the start again, but it will be much more efficient to read the lines into variable. 要多次读取文件,您必须在每回合之后调用file.seek(0)才能将迭代器再次移至起点,但是将这些行读入变量将更加有效。

you may be interested in file like objects and also may consider slice instead of the xrange 您可能对文件之类的对象感兴趣,也可能考虑使用slice而不是xrange

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM