go to specific line in text file

John Machin sjmachin at lexicon.net
Tue Jun 17 09:43:55 EDT 2008


On Jun 17, 10:46 pm, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> Patrick David <patrick.da... 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):

The OP gave no impression that he'd restrict himself to one
seek_to_line call per open. Perhaps you need
    f.seek(0)
here otherwise
    seek_to_line(f, 20)
    seek_to_line(f, 10)
will give something unexpected (like jumping forwards instead of
backwards).

>     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