python - 在单个表达式中读取文件,正确关闭它们
问题描述
我想在 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())
...这很冗长,而且读起来很长。
还有其他选择吗?
解决方案
您可以为此使用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()
推荐阅读
- autodesk-forge - Autodesk forge SVF2 dbid
- selenium-webdriver - 带有边缘浏览器的机器人框架
- python - Python检查列表中是否存在用于检测循环的列表
- python - 如何从 Python 中的 OLS 结果中获取因变量的信息?
- javascript - Redux Saga - yield spawn takeEvery 调用没有重载
- php - 使用 Bearer 令牌在 php 中使用 cURL 获取 DATA
- npm - NPM 安装输出在哪里?我在标准输出和标准错误中找不到它
- mpdf - Symfony 云 MPDF 临时文件不能存储在 /tmp
- wordpress - 如何收听 Gutenberg 区块中的事件?
- amazon-web-services - S3 - PutObject 导致 403 - 禁止 - 公共访问?