Russell Russell - 1 month ago 10
Python Question

Read first N lines of a file in python

We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.

How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the implementation?

Thanks :)

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

Here's another way

from itertools import islice
with open("datafile") as myfile:
    head = list(islice(myfile, N))
print head
Comments