Elegant way to skip first line when using python fileinput module?

The fileinput module contains a bunch of handy functions, one of which seems to do exactly what you're looking for:

for line in fileinput.input(["file.dat"]):
  if not fileinput.isfirstline():
    data = proces_line(line);
    output(data)

fileinput module documentation


It's right in the docs: http://docs.python.org/library/fileinput.html#fileinput.isfirstline


lines = iter(fileinput.input(["file.dat"]))
next(lines) # extract and discard first line
for line in lines:
    data = proces_line(line)
    output(data)

or use the itertools.islice way if you prefer

import itertools
finput = fileinput.input(["file.dat"])
lines = itertools.islice(finput, 1, None) # cuts off first line
dataset = (process_line(line) for line in lines)
results = [output(data) for data in dataset]

Since everything used are generators and iterators, no intermediate list will be built.

Tags:

Python

File Io