获取文件d的前N行

2024-03-28 21:07:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望获得python文件中的前n行数据。为了得到一行,我会做next(file);为了得到多行,我会做file.read(1024)''.join(file.readlines()[:1000]。你知道吗

在函数中实现这一点的最佳方法是什么?这是一个开始:

def get_first_n_rows(self, file, n=1):
    """
    Will return a string of the first N lines of data from the file.
    """
    s = ''
    with open(file, 'r') as f:
        for line in f:
            s += line
            if line == n: break
    return s

有没有更好的方法可以让我使用一个interator,比如next?你知道吗


Tags: 文件ofthe数据方法函数readreturn
2条回答

使用islice

from itertools import islice


def get_first_n_rows(self, file, n=1):
    """
    Will return a string of the first N lines of data from the file.
    """
    s = ''
    with open(file, 'r') as f:
        for line in islice(f, n):
            s += line
    return s

从链接的文档中:

Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped.

def get_first_n_rows(self, file, n=1):
    with open(file) as fp:
        return "".join(next(fp) for _ in range(0, n))

或者,如果您想要一个行列表:

def get_first_n_rows(self, file, n=1):
    with open(file) as fp:
        return list(next(fp) for _ in range(0, n))

相关问题 更多 >