如何读取文件的前 N 行?

新手上路,请多包涵

我们有一个大的原始数据文件,我们想将其修剪为指定的大小。

我将如何在 python 中获取文本文件的前 N 行?使用的操作系统是否会对实施产生任何影响?

原文由 Russell 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 359
2 个回答

蟒蛇 3:

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

蟒蛇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)

原文由 John La Rooy 发布,翻译遵循 CC BY-SA 4.0 许可协议

N = 10
with open("file.txt", "a") as file:  # the a opens it in append mode
    for i in range(N):
        line = next(file).strip()
        print(line)

原文由 ghostdog74 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题