gurehbgui
gurehbgui

Reputation: 14684

how to start reading at line X in python?

actually I read a file like this:

f = open("myfile.txt")
for line in f:
    #do s.th. with the line

what do I need to do to start reading not at the first line, but at the X line? (e.g. the 5.)

Upvotes: 1

Views: 882

Answers (2)

Jon Clements
Jon Clements

Reputation: 142156

Using itertools.islice you can specify start, stop and step if needs be and apply that to your input file...

from itertools import islice

with open('yourfile') as fin:
    for line in islice(fin, 5, None):
        pass

Upvotes: 9

eumiro
eumiro

Reputation: 212885

An opened file object f is an iterator. Read (and throw away) the first four lines and then go on with regular reading:

with open("myfile.txt", 'r') as f:
    for i in xrange(4):
        next(f, None)
    for line in f:
        #do s.th. with the line

Upvotes: 8

Related Questions