Python:使用 "with"打开压缩或解压缩文件

标签 python with-statement

我正在寻找使用“with”打开文件的解决方案。然而,我想检查文件是否被 gzip 压缩,然后使用 gzip.open 或只是打开类似的内容:

if f.endswith(".gz"):
    with gzip.open() as f:
else:
    with open() as f:
for line in f:

有什么想法吗?

最佳答案

实现此目的的一种方法是创建自己的上下文管理器来为您完成此操作。

from contextlib import contextmanager

@contextmanager
def open_file(filename):
    if filename.endswith(".gz"):
        with gzip.open(filename) as f:
            yield f
    else:
        with open(filename) as f:
            yield f

然后您就可以使用它来打开文件。

with open_file("filename") as f:
    # f will be either the result of `gzip.open` or `open`, depending on its filename.
    for line in f:
        pass  

这使您能够保留使用 with 子句的优点,同时使您能够灵活地选择要调用的函数。

关于Python:使用 "with"打开压缩或解压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47643978/

相关文章:

python - 我应该如何从 with 语句返回有趣的值?

javascript - 在上下文中使用 with 语句是个好主意吗?

python - 通过 python setup.py 创建 .deb 包

python - Pandas 相关矩阵与 value_counts 列字符串

python - 在keras中对合并层进行训练

python - 同时与多列进行复杂比较

python - With 语句的数量可变

python - 上下文管理器反向

python - 我的自定义模块没有出现在我的 openerp 7 安装中

python - 用 with 语句关闭后重新打开 sys.stdout