Read the top n lines of a file in Python

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:

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:

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()
Tags:

Leave a Reply

Your email address will not be published.