Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Add Files to a TAR File Using Python



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

Different File Modes to Create a tar file

Here are the available different 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 File

Following is the example, in which we create a tar file and add a single file with the help of the tarfile module available in Python along with the open() function by using the 'w' mode and add() method -

import tarfile

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

The above program creates a tar file with the name TutorialsPoint and adds a single file -

Adding Multiple Files to a tar file

Here is an example that loops through a list of files and adds them to a tar archive by using the open() and add() functions available in Python -

import tarfile

files = ["file1.txt", "file2.txt", "notes.docx"]

with tarfile.open("multi_files.tar", "w") as tar:
   for file in files:
      tar.add(file)

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

Adding a Directory Recursively

Here in this example, we will add a folder and all its subfiles and subfolders recursively using the open() and add() functions -

import tarfile

with tarfile.open("backup_folder.tar.gz", "w:gz") as tar:
   tar.add("my_project", arcname="my_project")

Note: The arcname parameter allows us to rename the folder inside the archive.

Updated on: 2025-05-27T18:14:57+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements