How to Compress a Tarfile in Python?

Estimated read time 2 min read

To compress a tar file using Python, you can utilize the tarfile module, which provides functions for creating and manipulating tar archives. Here’s an example of how you can compress a tar file:

import tarfile

def compress_tarfile(input_path, output_path):
    with, 'w:gz') as tar:
        tar.add(input_path, arcname='compressed.tar')

# Example usage
input_path = 'folder_to_compress'
output_path = 'compressed.tar.gz'

compress_tarfile(input_path, output_path)

In this example, the compress_tarfile() function takes two parameters: the input path of the folder or directory to be compressed, and the output path for the compressed tar file. The function uses the method to create a new tar file in write mode with gzip compression ('w:gz').

Within the context of the with statement, you can add the contents of the input folder to the tar file using the tar.add() method. The arcname argument specifies the name of the file within the archive.

After executing the code, you will have a compressed tar file (compressed.tar.gz) containing the contents of the input folder.

You can adjust the compression method by changing the mode passed to For example, you can use 'w:bz2' for bzip2 compression or 'w:xz' for xz compression.

Make sure you have the necessary permissions to access the input folder and write to the output path.

Note that the tarfile module can also be used to extract and manipulate existing tar archives.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply