How to read first N lines of a file?
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)
N = 10
with open("file.txt", "a") as file: # the a opens it in append mode
for i in range(N):
line = next(file).strip()
print(line)