1 min read

Python Tarfile Module

The tarfile module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression.

Importing the Module

import tarfile

Reading Tar Files

To open a tar file for reading, use tarfile.open().

import tarfile

with tarfile.open('example.tar', 'r') as tar:
    # List all files in archive
    for member in tar.getmembers():
        print(member.name)

    # Extract all files
    tar.extractall(path="extracted_files")

Writing Tar Files

To create a new tar file, open it in write mode ('w').

import tarfile

with tarfile.open('sample.tar', 'w') as tar:
    tar.add('file.txt')
    tar.add('directory_name')

Compression

You can create compressed archives by specifying the compression mode in open().

  • 'w:gz': Open for gzip compressed writing.
  • 'w:bz2': Open for bzip2 compressed writing.
  • 'w:xz': Open for lzma compressed writing.
import tarfile

with tarfile.open('sample.tar.gz', 'w:gz') as tar:
    tar.add('file.txt')

Appending to Tar Files

To append to an existing tar file, use mode 'a'. Note that appending is not possible for compressed archives.

import tarfile

with tarfile.open('sample.tar', 'a') as tar:
    tar.add('another_file.txt')

programming/python/python