我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。

如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?


当前回答

这对我很有效

f = open("history_export.csv", "r")
line= 5
for x in range(line):
    a = f.readline()
    print(a)

其他回答

这适用于Python 2和3:

from itertools import islice

with open('/tmp/filename.txt') as inf:
    for line in islice(inf, N, N+M):
        print(line)

Python 3:

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

Python 2:

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

下面是另一种方法(Python 2和3都是):

from itertools import islice

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

我自己最方便的方法:

LINE_COUNT = 3
print [s for (i, s) in enumerate(open('test.txt')) if i < LINE_COUNT]

基于列表理解的解决方案 函数open()支持迭代接口。enumerate()包含open()和return元组(index, item),然后检查是否在可接受的范围内(如果i < LINE_COUNT),然后简单地打印结果。

欣赏Python。;)

这里有另一个不错的解决方案与列表理解:

file = open('file.txt', 'r')

lines = [next(file) for x in range(3)]  # first 3 lines will be in this list

file.close()

有一个简单的方法来获取前10行:

with open('fileName.txt', mode = 'r') as file:
    list = [line.rstrip('\n') for line in file][:10]
    print(list)