python – 声明:with和tarfile

我尝试使用语句和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, in
AttributeError: '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(或者甚至更早的…).

翻译自:https://stackoverflow.com/questions/6086603/statement-with-and-tarfile

转载注明原文:python – 声明:with和tarfile