How to create full compressed tar file using Python?

compression, python, tarfile, zip

Solution

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`.

Problem

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

Original source

Related problems