Thursday, February 19, 2026
HomeLanguagesHow to uncompress a “.tar.gz” file using Python ?

How to uncompress a “.tar.gz” file using Python ?

.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.

In order to extract or un-compress “.tar.gz” files using python, we have to use the tarfile module in python. This module can read and write .tar files including .gz, .bz compression methods.

Approach

  • Import module
  • Open .tar.gz file
  • Extract file in a specific folder
  • Close file

File in use

Name: gfg.tar.gz 

Link to download this file: Click here

Contents:

“gfg.tar.gz” file

Example:

Python3




# importing the "tarfile" module
import tarfile
  
# open file
file = tarfile.open('gfg.tar.gz')
  
# extracting file
file.extractall('./Destination_FolderName')
  
file.close()


Output:

A folder named “Destination_Folder” is created.

Files are uncompressed inside the “Destination_Folder”

Example: Printing file names before extracting

Python3




# importing the "tarfile" module
import tarfile
  
# open file
file = tarfile.open('gfg.tar.gz')
  
# print file names
print(file.getnames())
  
# extract files
file.extractall('./Destination_FolderName')
  
# close file
file.close()


Output:

Example : Extract a specific file

Python3




# importing the "tarfile" module
import tarfile
  
# open file
file = tarfile.open('gfg.tar.gz')
  
# extracting a specific file
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”

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS