Open In App

How to uncompress a ".tar.gz" file using Python ?

Last Updated : 27 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

.tar.gz files are made by the combination of TAR packaging followed by a GNU zip (gzip) compression. These files are commonly used in Unix/Linux based system as packages or installers. In order to read or extract these files, we have to first decompress these files and after that expand them with the TAR utilities as these files contain both .tar and .gz files. Below, we use a sample file named "gfg.tar.gz" to demonstrate how to work with such archives in Python.

Link to download this file: Click here

"gfg.tar.gz" file

Using tarfile module

Tarfile module in Python is a built-in library used to read from and write to tar archive files, including compressed versions like .tar.gz, .tar.bz2 and .tar.xz. It allows Python programs to create, extract, list and manipulate tar archives seamlessly without requiring external tools.

Example 1: This example shows how to open a .tar.gz file and extract all its contents into a specified folder.

Python
import tarfile
file = tarfile.open('gfg.tar.gz') 

file.extractall('./Destination_FolderName') 
file.close()

Output

A folder named "Destination_Folder" is created.
Files are uncompressed inside the "Destination_Folder"

Explanation: This code opens the gfg.tar.gz archive using the tarfile module, extracts all its contents into the Destination_FolderName folder creating it if it doesn't exist and then closes the archive.

Example 2: This example demonstrates how to list all the filenames inside the archive before extracting them.

Python
import tarfile
file = tarfile.open('gfg.tar.gz')

print(file.getnames())
file.extractall('./Destination_FolderName')
file.close()

Output

Explanation: This code opens the gfg.tar.gz archive using the tarfile module, prints the list of all files inside the archive, extracts all its contents into the Destination_FolderName folder creating it if it doesn't exist and then closes the archive.

Example 3: This example shows how to extract only a specific file (sample.txt) from the archive.

Python
import tarfile
file = tarfile.open('gfg.tar.gz')

file.extract('sample.txt', './Destination_FolderName')
file.close()

Output

A new folder named "Destination_FolderName" is created
'sample.txt' is uncompressed inside the "Destination_FolderName"

Explanation: This code opens the gfg.tar.gz archive using the tarfile module, extracts only the sample.txt file into the Destination_FolderName folder creating it if it doesn't exist and then closes the archive.


Next Article

Similar Reads