首页 > 解决方案 > 在单个表达式中读取文件,正确关闭它们

问题描述

我想在 python 中读取文件列表的内容。我的第一个想法是

contents = [open(f).read() for f in files]

但这会使文件保持打开状态,直到对象被垃圾收集,并显示ResourceWarning.

关闭文件需要多种理解:

fds = [open(f) for f in files]
contents = [fd.read() for fd in fds]
[fd.close() for fd in fds]

...这是不自然的。

或循环:

contents = []
for f in files:
    with open(f) as fd:
        contents.append(f.read())

...这很冗长,而且读起来很长。

还有其他选择吗?

标签: pythonfileexpressionlist-comprehensioncontextmanager

解决方案


您可以为此使用pathlib

from pathlib import Path
contents_text = [Path(f).read_text() for f in files]
contents_bytes = [Path(f).read_bytes() for f in files]

里面只有:

class Path:

    # ....

    def read_bytes(self):
        """
        Open the file in bytes mode, read it, and close the file.
        """
        with self.open(mode='rb') as f:
            return f.read()

    def read_text(self, encoding=None, errors=None):
        """
        Open the file in text mode, read it, and close the file.
        """
        with self.open(mode='r', encoding=encoding, errors=errors) as f:
            return f.read()

推荐阅读