How are files added to a tar file using Python?

Python offers a built-in module named tarfile, which allows developers to create, read, and modify tar archives (standard Unix tarballs). We can use this module to compress multiple files into a single archive, with or without compression.

File Modes for Creating Tar Archives

Here are the available file modes to create a tar file using Python ?

  • "w": Write a tar archive without compression.
  • "w:gz": Write a gzip-compressed archive.
  • "w:bz2": Write a bzip2-compressed archive.
  • "w:xz": Write an xz-compressed archive (Python 3.3+).

Adding a Single File to a Tar Archive

The following example shows how to create a tar file and add a single file using the tarfile module ?

import tarfile

# Create a sample file first
with open("notes.txt", "w") as f:
    f.write("This is a sample text file for the tar archive.")

# Create a .tar archive file and add the single file
with tarfile.open("TutorialsPoint.tar", "w") as tar:
    tar.add("notes.txt")

print("Single file added to TutorialsPoint.tar successfully!")
Single file added to TutorialsPoint.tar successfully!

The above program creates a tar file named TutorialsPoint.tar and adds the single file notes.txt to it.

Adding Multiple Files to a Tar Archive

Here is an example that loops through a list of files and adds them to a tar archive ?

import tarfile

# Create sample files first
sample_files = ["file1.txt", "file2.txt", "notes.txt"]

for i, filename in enumerate(sample_files):
    with open(filename, "w") as f:
        f.write(f"This is content for {filename}")

# Add multiple files to tar archive
with tarfile.open("multi_files.tar", "w") as tar:
    for file in sample_files:
        tar.add(file)

print("Multiple files added to multi_files.tar successfully!")
Multiple files added to multi_files.tar successfully!

When we execute the above program, all the defined files will be added to the multi_files.tar file.

Adding a Directory Recursively

The following example shows how to add a folder and all its subfiles and subfolders recursively ?

import tarfile
import os

# Create a sample directory structure
os.makedirs("my_project/subfolder", exist_ok=True)

with open("my_project/main.py", "w") as f:
    f.write("print('Hello from main.py')")

with open("my_project/subfolder/config.txt", "w") as f:
    f.write("Configuration settings")

# Add directory recursively to compressed tar archive
with tarfile.open("backup_folder.tar.gz", "w:gz") as tar:
    tar.add("my_project", arcname="my_project")

print("Directory added to backup_folder.tar.gz successfully!")
Directory added to backup_folder.tar.gz successfully!

Note: The arcname parameter allows us to rename the folder inside the archive. This example creates a gzip-compressed tar file containing the entire directory structure.

Adding Files with Custom Archive Names

You can also add files with different names inside the archive using the arcname parameter ?

import tarfile

# Create a sample file
with open("original.txt", "w") as f:
    f.write("This file will have a different name in the archive.")

# Add file with custom name in archive
with tarfile.open("custom_names.tar", "w") as tar:
    tar.add("original.txt", arcname="renamed_file.txt")

print("File added with custom name to archive!")
File added with custom name to archive!

Conclusion

Python's tarfile module provides a simple way to create tar archives and add files or directories to them. Use the add() method to include files, and the arcname parameter to customize names within the archive.

Updated on: 2026-03-24T18:42:13+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements