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)
Code language: Python (python)

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()
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments