How are files added to a tar file using Python?

Use the tarfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively.

For example

import os
import tarfile
def tardir(path, tar_name):
    with, "w:gz") as tar_handle:
        for root, dirs, files in os.walk(path):
            for file in files:
                tar_handle.add(os.path.join(root, file))
tardir('./my_folder', 'sample.tar.gz')

The above code will compress the contents of my_folder in a file 'sample.tar.gz'. and store it in the current directory.