python - 从 Python 中的 Generator 类生成 n 行

标签 python python-3.x generator

我想在每次调用 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)

这只是返回所有行。

最佳答案

您可以实现一个 __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())

关于python - 从 Python 中的 Generator 类生成 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58200007/

相关文章:

python - 使用 flask-sqlalchemy 创建应用程序模式

Python-将字典中的两个列表相减

python-3.x - 如何使用selenium重新连接到webdriver打开的浏览器?

python - python生成器可以使用递归吗?

python - psutil.Process 和 lsof 命令差异

python - 努力在Python中将时区GMT转换为CST

python - 从子进程调用中获取退出代码和标准错误

php - 给定字符生成器和长度,如何生成所有可能字符串的列表?

python - izip 内的 izip : unpacking generators?

python - 为 ARM 与 x86 编写代码时有何区别?