Using xreadlines

bearophileHUGS at bearophileHUGS at
Thu Feb 26 20:09:22 EST 2009

Brett Hedges:
> My question is how do I go to a previous line in the file? xreadlines has a statement that gives the next line, and I need a statement that gives me the previous line.<

In modern versions of Python you usually don't need xreadlines,
because files are iterable.

If your files are small, you can just read all the lines in a list
with open(...).readlines(), and then just use the item of the list
with the n-1 index.

If the file is quite large or you like to keep things lazy, then you
have to keep memory of the previous line, using an auxiliary variable.
You can also wrap this idiom into a generator function (or iterable
class, probably) that yields items and keeps memory of the last one
(but you can't ask the previous of the first item, of course).

You can also keep track of the absolute position of the lines in the
file, etc, or step back looking for newlines, etc, but it's not handy.


More information about the Python-list mailing list