Read file from line 2 or skip header row in Python

This post introduces how to read file from line 2 in Python.

  • method 1:
with open(fname) as f:
  next(f)
  for line in f:
    #do something

Note: If you need the header later, instead of next(f) use f.readline() and store it as a variable.
Or use header_line = next(f).

  • method 2
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

This will skip 1 line. for example, [‘a’, ‘b’, ‘c’][1:] => [‘b’, ‘c’]

 

Leave a Reply

Your email address will not be published. Required fields are marked *