如何读取文件的前N行? [英] How to read first N lines of a file?
本文介绍了如何读取文件的前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?
推荐答案
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)
这篇关于如何读取文件的前N行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文