在python中读取文件的前N行

问题描述:

我们有一个大的原始数据文件,我们希望修剪到指定的大小。
我有经验的.net c#,但是希望在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.

python中的文本文件的前N行?
正在使用的操作系统是否对实现有任何影响?

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?

感谢:)

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

这是另一种方式

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