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

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


当前回答

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)

其他回答

我自己最方便的方法:

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。;)

最直观的两种方法是:

逐行迭代文件,并在N行之后进行换行。 使用next()方法逐行迭代文件N次。(这本质上只是顶部答案的不同语法。)

代码如下:

# Method 1:
with open("fileName", "r") as f:
    counter = 0
    for line in f:
        print line
        counter += 1
        if counter == N: break

# Method 2:
with open("fileName", "r") as f:
    for i in xrange(N):
        line = f.next()
        print line

底线是,只要不使用readlines()或将整个文件枚举到内存中,您就有很多选择。

我想通过读取整个文件来处理小于n行的文件

def head(filename: str, n: int):
    try:
        with open(filename) as f:
            head_lines = [next(f).rstrip() for x in range(n)]
    except StopIteration:
        with open(filename) as f:
            head_lines = f.read().splitlines()
    return head_lines

这要归功于约翰·拉·鲁伊和伊莲·伊利耶夫。使用异常句柄函数以获得最佳性能

修改1:感谢FrankM的反馈,处理文件存在和读取权限我们可以进一步增加

import errno
import os

def head(filename: str, n: int):
    if not os.path.isfile(filename):
        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename)  
    if not os.access(filename, os.R_OK):
        raise PermissionError(errno.EACCES, os.strerror(errno.EACCES), filename)     
   
    try:
        with open(filename) as f:
            head_lines = [next(f).rstrip() for x in range(n)]
    except StopIteration:
        with open(filename) as f:
            head_lines = f.read().splitlines()
    return head_lines

您可以使用第二个版本,也可以使用第一个版本,稍后再处理文件异常。从性能的角度来看,检查是快速的,而且大部分是免费的

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)

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

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