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

Extract Files from a Tar File Using Python



A TAR file is abbreviated as Tape Archive, which is an archive format used mainly in Unix and Linux environments. The Tar file is used to collect more number of files into a single file, which makes it easier to share or backup together.

In Python, when we want to work with TAR files, we can use the tarfile module, which allows us to create, read and extract TAR archives programmatically.

In this article, we will explore how to extract the files from tar file by using Python.

Extracting all files from a"tar" file

The extractall() method in Python is used to extract all the files or folders of the archive into the current path if any other path is not defined.

Example

Following is the example, which uses the extractall() method to extract all the available files from the defined tar file -

import tarfile
with tarfile.open('sample.tar', 'r') as tar:
    tar.extractall(path=r'D:\Tutorialspoint\Articles\tar_extracted')
    print("All files extracted successfully.")

Following is the output of the above program -

D:/Tutorialspoint/Articles/tar_extracted/
??? file1.txt
??? file2.txt
??? folder/
    ??? python_file.py
All files extracted successfully.

Extracting a Single File from Tar File

The extract() method in Python is used to extract a specific file from a TAR archive. This is useful when we don't want to extract the entire archive but only one particular file.

Example

Below is the example which uses the extract() method to extract a single file named file1.txt from the sample.tar archive -

import tarfile
with tarfile.open('sample.tar', 'r') as tar:
    tar.extract('file1.txt', path=r'D:\Tutorialspoint\Articles\tar_single')
    print("Single file extracted successfully.")

Following is the output of the above program -

D:/Tutorialspoint/Articles/tar_single/
??? file1.txt
Single file extracted successfully.
Updated on: 2025-05-28T17:28:12+05:30

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements