Python 获取文件数据的前N行

Python 获取文件数据的前N行,python,python-3.x,Python,Python 3.x,我希望获得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. """

我希望获得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

使用:

从链接的文档中:

生成一个迭代器,从iterable返回所选元素。如果 start为非零,则将跳过iterable中的元素,直到 到达start。之后,连续返回元素 除非步骤设置高于导致项目被删除的步骤 跳过

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

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

谢谢,请您简要解释一下islice的功能,或者链接到文档等。
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))