python - 这是一个可接受的 pythonic 习语吗?

标签 python

我有一个类可以帮助导入特殊类型的文件,还有一个“工厂”类可以让我批量执行这些操作。工厂类使用生成器,因此客户端可以遍历导入器。 我的问题是,我是否正确使用了迭代器?这是可以接受的成语吗?我刚开始使用 Python。

class FileParser:
  """ uses an open filehandle to do stuff """

class BatchImporter:
  def __init__(self, files):
    self.files=files

  def parsers(self):
    for file in self.files:
      try:
        fh = open(file, "rb")
        parser = FileParser(fh)
        yield parser
      finally:
        fh.close()

  def verifyfiles(
  def cleanup(

---

importer = BatchImporter(filelist)
for p in BatchImporter.parsers():
  p.method1()
  ...

最佳答案

您可以使一件事变得更简单:使用 with block 代替 try...finally:

with open(file, "rb") as fh:
    yield FileParser(fh)

这将在 with block 离开时自动为您关闭文件。

关于python - 这是一个可接受的 pythonic 习语吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3283479/

相关文章:

python - Groupby 值对数据框 pandas 的计数

python - 枚举命名元组

python - Python-使用yield停止无限循环,然后重定向

Python 在 futex 调用中挂起

python - 在 Tensorflow 中表示 3 维张量

python - 我从哪里获得 Authorized Gmail API 服务实例? ( python ,Gmail API)

python - 如何根据 pandas DataFrame 中的长度过滤 session

python - 计算唯一对并将计数存储在矩阵中

python - 请求有效而 URLFetch 无效

python - 如何创建自定义嵌套字典?