Skip first couple of lines while reading lines in Python file Skip first couple of lines while reading lines in Python file python python

Skip first couple of lines while reading lines in Python file


Use a slice, like below:

with open('yourfile.txt') as f:    lines_after_17 = f.readlines()[17:]

If the file is too big to load in memory:

with open('yourfile.txt') as f:    for _ in range(17):        next(f)    for line in f:        # do stuff


Use itertools.islice, starting at index 17. It will automatically skip the 17 first lines.

import itertoolswith open('file.txt') as f:    for line in itertools.islice(f, 17, None):  # start=17, stop=None        # process lines


for line in dropwhile(isBadLine, lines):    # process as you see fit

Full demo:

from itertools import *def isBadLine(line):    return line=='0'with open(...) as f:    for line in dropwhile(isBadLine, f):        # process as you see fit

Advantages: This is easily extensible to cases where your prefix lines are more complicated than "0" (but not interdependent).