python - 从 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)
这只是返回所有行。
解决方案
你可以实现一个__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 等价于 rpm -Va
- ios - 如何按日期对消息进行分组?
- azure-notebooks - 真的没有办法在 Azure Notebooks 中私下共享库吗?
- bash - 在多个 FASTA 文件中查找和替换多个序列头
- java - Android Studio 3.1.3 - 未解决的参考:R - Kotlin
- python - Bag of Words (BOW) vs N-gram (sklearn CountVectorizer) - 文本文档分类
- sql - 我可以(应该)在同一个 select 语句中包含 TO_CHAR、CONCAT 和 FM 的元素吗?
- mysql - 在日期范围上使用 SUM 和 GROUP BY 时如何在空结果上返回零
- c# - 如何序列化列表
c# 中的属性而不在 XML 序列化中显示其类型 - java - 我必须为我创建的每个组件创建一个单独的 ActionListener 吗?