speed up linecache.getline()

Peter Otten __peter__ at web.de
Tue Oct 13 16:32:50 CEST 2009

bbarbero at inescporto.pt wrote:

> I am using linecache.getline, to access to a line in a long file. It s
> really fast, appx 4seconds, but I was just wandering if any of you,
> know either another way, or there is something that I can do to speed
> it up...  thank you very much for your help!!

If it is a single file that never changes just read it into a list:

with open(filename) as f:
    cached_lines = list(f)

If that alone takes about 4 seconds the runtime of your script is spent 
reading the file from disk. An SSD might help then ;)

In some situations you could delay reading line n until that line is 
actually needed. This may speed up your script for cases where all requested 
lines are near the beginning of the cached file.


More information about the Python-list mailing list