更新时间:2023-08-26 18:35:46
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)
这是另一种方式( Python 2和3 ):
from itertools import islice
with open("datafile") as myfile:
head = list(islice(myfile, N))
print(head)