Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statement: with and tarfile

Tags:

python

I try to use with statement and tarfile module...

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

So it shows the next:

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

I try to create tar.gz file and close it using statement is, but it show an error. What is the problem?

Thanks!

like image 817
ouea Avatar asked May 22 '11 07:05

ouea


People also ask

How do I open a Tarfile file in Python?

You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.


1 Answers

You can use contextlib.closing, e.g.:

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

From docs:

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

contextlib.closing is available since Python 2.5 (or maybe even earlier...).

like image 64
mechanical_meat Avatar answered Sep 21 '22 12:09

mechanical_meat