Fast way to grab line from file?

Skip Montanaro skip at
Mon Feb 21 21:31:37 EST 2000

    Mateo> Does anyone know of a faster way to grab line 100 from a given
    Mateo> file without doing 100 readline() calls? This way is too slow,
    Mateo> but I can't find out how to do this in python. Thanks,

Unless your file has records of fixed length, you won't be able to do
terrifically better.  Somewhere along the way, something is going to have to
count 99 end of lines and realize, "aha! here's line 100".  With
fixed-length records you can obviously seek to the offset that starts the
line of interest.

You might be able to speed things up sufficiently using the sizehint
argument to a file object's readlines method.  Your logic will be a bit more
complex, but shouldn't be exceedingly difficult.  Check out

Skip Montanaro |
skip at |
"Languages that change by catering to the tastes of non-users tend not to do
so well." - Doug Landauer

More information about the Python-list mailing list