python: how to jump to a particular line in a huge text file?

Posted by photographer on Stack Overflow See other posts from Stack Overflow or by photographer
Published on 2009-03-06T20:49:52Z Indexed on 2010/04/28 7:43 UTC
Read the original article Hit count: 353

Filed under:
|

Are there any alternatives to the code below:

startFromLine = 141978 # or whatever line I need to jump to

urlsfile = open(filename, "rb", 0)

linesCounter = 1

for line in urlsfile:
    if linesCounter > startFromLine:
        DoSomethingWithThisLine(line)

    linesCounter += 1

if I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.

© Stack Overflow or respective owner

Related posts about python

Related posts about textfiles