Fix Python – How to create full compressed tar file using Python?

Question

Asked By – shahjapan

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

Now we will see solution for issue: How to create full compressed tar file using Python?


Answer

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.

This question is answered By – George V. Reilly

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0