Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file starting from the second line in python

Tags:

python

file

io

I use python and I don't know how to do.

I want to read lots of lines in files. But I have to read from second lines. All files have different lines, So I don't know how to do.

Code example is that it read from first line to 16th lines. But I have to read files from second lines to the end of lines. Thank you!:)

with open('filename') as fin:
  for line in islice(fin, 1, 16):
    print line
like image 607
KyungWook Avatar asked Dec 07 '22 16:12

KyungWook


2 Answers

You should be able to call next and discard the first line:

with open('filename') as fin:
    next(fin) # cast into oblivion
    for line in fin:
        ... # do something

This is simple and easy because of the nature of fin, being a generator.

like image 92
cs95 Avatar answered Dec 11 '22 09:12

cs95


with open("filename", "rb") as fin:
    print(fin.readlines()[1:])
like image 27
Viren Dholakia Avatar answered Dec 11 '22 10:12

Viren Dholakia