Read the top n lines of a file in Python

0 min read 99 words

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:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags