go to specific line in text file

Hrvoje Niksic hniksic at xemacs.org
Tue Jun 17 14:46:28 CEST 2008


Patrick David <patrick.david at tu-clausthal.de> writes:

> I am searching for a way to jump to a specific line in a text file,
> let's say to line no. 9000.  Is there any method like file.seek()
> which leads me to a given line instead of a given byte?

You can simulate it fairly easily, but it will internally read the
file line by line and will take the time roughly proportional to the
size of the file.

from itertools import islice
def seek_to_line(f, n):
    for ignored_line in islice(f, n - 1):
        pass   # skip n-1 lines

f = open('foo')
seek_to_line(f, 9000)    # seek to line 9000

# print lines 9000 and later
for line in f:
    print line



More information about the Python-list mailing list