且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何读取文件的前N行?

更新时间: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)