How to read first N lines of a file? How to read first N lines of a file? python python

How to read first N lines of a file?


Python 2:

with open("datafile") as myfile:    head = [next(myfile) for x in xrange(N)]print head

Python 3:

with open("datafile") as myfile:    head = [next(myfile) for x in range(N)]print(head)

Here's another way (both Python 2 & 3):

from itertools import islicewith open("datafile") as myfile:    head = list(islice(myfile, N))print(head)


N = 10with open("file.txt", "a") as file:  # the a opens it in append mode    for i in range(N):        line = next(file).strip()        print(line)


If you want to read the first lines quickly and you don't care about performance you can use .readlines() which returns list object and then slice the list.

E.g. for the first 5 lines:

with open("pathofmyfileandfileandname") as myfile:    firstNlines=myfile.readlines()[0:5] #put here the interval you want

Note: the whole file is read so is not the best from the performance point of view but it is easy to use, fast to write and easy to remember so if you want just perform some one-time calculation is very convenient

print firstNlines

One advantage compared to the other answers is the possibility to select easily the range of lines e.g. skipping the first 10 lines [10:30] or the lasts 10 [:-10] or taking only even lines [::2].