Read first N lines of a file in python


Question

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?

1
133
6/7/2018 1:43:40 PM

Accepted Answer

Python 2

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

Python 3

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

Here's another way (both Python 2 & 3)

from itertools import islice
with open("datafile") as myfile:
    head = list(islice(myfile, N))
print head
215
11/27/2018 11:58:59 PM

N = 10
file = open("file.txt", "a")#the a opens it in append mode
for i in range(N):
    line = file.next().strip()
    print line
file.close()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon