gpt4 book ai didi

python - 语句 : with and tarfile

转载 作者:太空狗 更新时间:2023-10-29 16:55:09 25 4
gpt4 key购买 nike

我尝试使用 with 语句和 tarfile 模块...

with tarfile.open('/dir/dir/dir.tar.gz', 'w:gz') as fl:
fl.add('/dir/dir/dir/', arcname = '/')

所以它显示下一个:

Traceback (most recent call last):File "", line 1, inAttributeError: 'TarFile' object has no attribute '__exit__'

我尝试创建 tar.gz 文件并使用语句关闭它,但它显示错误。有什么问题?

谢谢!

最佳答案

您可以使用 contextlib.closing ,例如:

from contextlib import closing
with closing(tarfile.open('/dir/dir/dir.tar.gz', 'w:gz')) as fl:
fl.add('/dir/dir/dir/', arcname = '/')

来自文档:

Even if an error occurs, page.close() will be called when the with block is exited.

contextlib.closing 自 Python 2.5(或什至更早...)以来可用。

关于python - 语句 : with and tarfile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6086603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com