Home » Python » Read file from line 2 or skip header row

Read file from line 2 or skip header row

Posted by: admin November 1, 2017 Leave a comment

Questions:

How can I skip the header row and start reading a file from line2?

Answers:
with open(fname) as f:
    next(f)
    for line in f:
        #do something

Questions:
Answers:
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

Questions:
Answers:

If you want the first line and then you want to perform some operation on file this code will helpful.

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

Questions:
Answers:
f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
    ...

Questions:
Answers:
 with open('old.csv', 'r') as f, open('new.csv', 'w') as ff:
    first_line = f.readline()
    for line in f:
        line = line.translate({ord(i):None for i in 'abcd'})
        ff.write(line)
    ff.seek(0)
    ff.write(first_line)

Questions:
Answers:

If slicing could work on iterators…

from itertools import islice
with open(fname) as f:
    for line in islice(f, 1, None):
        pass