views:

299

answers:

3

how can I create a .tar.gz file which compress the data as much tar can...

A: 

tarfile module is cool: http://docs.python.org/library/tarfile.html

jspcal
+1  A: 
import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
    tar.add(name)
tar.close()

If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2".

CNBorn
+3  A: 

You call tarfile.open with mode='w:gz', meaning "Open for gzip compressed writing."

You'll probably want to end the filename (the name argument to open) with .tar.gz, but that doesn't affect compression abilities.

BTW, you usually get better compression with a mode of 'w:bz2', just like tar can usually compress even better with bzip2 than it can compress with gzip.

Alex Martelli
Just a quick note that the filename for bzip2-compressed tarballs should end with ".tar.bz2".
Ignacio Vazquez-Abrams