gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:54:56 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com