Sometimes you may need to read the top n lines of a file using Python.

We start by opening the file for reading and then using a list comprehension we iterate through the range of lines we want to return:

1
2
3
4
5
6
7
N = 10
filename = "file.txt"

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

print(head)

Another way you can do this is by looping through each line individually:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
N = 10
filename = "file.txt"

file = open(filename)
for i in range(N):
    line = file.next().strip()
    print(line)

# make sure to close the file when you're done
file.close()