Index out of range for simple `readlines` operation in Python

后端 未结 1 476
盖世英雄少女心
盖世英雄少女心 2021-01-29 04:25

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,         


        
相关标签:
1条回答
  • 2021-01-29 04:51

    The reason it works in your second example is because you call readlines() only once.

    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.

    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.

    you may be interested in file like objects and also may consider slice instead of the xrange

    0 讨论(0)
提交回复
热议问题