首页 > 解决方案 > 从 Python 中的 Generator 类中产生 n 行

问题描述

每次调用 Generator 类时,我都想从文件中打印 n 行。

我尝试了以下方法:

class FileReader:
    def __init__(self, file):
        with open(file, 'r') as fin:
            read_file = fin.read()

            # gen-comp yielding stripped lines
            lines = (line.strip() for line in read_file)
            print(lines)

这只是返回所有行。

标签: pythonpython-3.xgenerator

解决方案


你可以实现一个__call__方法,比如,

import sys
from itertools import islice

class FileReader:
    def __init__(self, fname, len=3):
        self.fname = fname
        self._len = len

    def __enter__(self):
        self.fd = open(self.fname, 'r')
        return self

    def __call__(self):
        return list(islice(self.fd, self._len))

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.fd:
            self.fd.close()


with FileReader(sys.argv[1]) as f:
    print(f())
    print(f())

推荐阅读