How to create full compressed tar file using Python?

shahjapan picture shahjapan · Jan 9, 2010 · Viewed 103.9k times · Source

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

Answer

George V. Reilly picture George V. Reilly · Jun 13, 2013

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.