How to read first N lines of a file with Python?

Sometimes, we want to read first N lines of a file with Python.

In this article, we’ll look at how to read first N lines of a file with Python.

How to read first N lines of a file with Python?

To read first N lines of a file with Python, we can use the next function.

For instance, we write

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

to call open to read the datafile file.

Then we call next with the myfile file to read the first N lines by putting next in the for loop.

Conclusion

To read first N lines of a file with Python, we can use the next function.