Alex Rivera | Logout

How to create full compressed tar file using Python?

Asked 2010-01-09T04:59:37.020
191

How can I create a .tar.gz file with compression in Python?

Edit
Report

2 Answers

323

To build a .tar.gz (aka .tgz) for an entire directory tree:

import tarfile
import os.path

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))

This will create a gzipped tar archive containing a single top-level folder with the same name and contents as source_dir.

answered 2013-06-13T06:58:45.260
115
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".

answered 2010-01-09T05:17:44.973

Your Answer