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

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

To uncompress a .tar.gz file in Python, you can use the tarfile module. Here's a step-by-step guide on how to do this:

  • Import the necessary module:
import tarfile 
  • Write a function to extract the .tar.gz file:
def extract_tar_gz(file_path, output_path='.'): with tarfile.open(file_path, 'r:gz') as file: file.extractall(path=output_path) 
  • Use the function:

Given a .tar.gz file named sample.tar.gz, you can extract it to the current directory like this:

extract_tar_gz('sample.tar.gz') 

Or, if you want to extract it to a specific directory, provide that as the second argument:

extract_tar_gz('sample.tar.gz', output_path='/path/to/extracted/files') 

That's it! The tarfile module handles both the decompression (from .gz) and the extraction (from .tar) for you.


More Tags

mongoid type-conversion formarray postdata fft tablename angular-bootstrap unsafe-pointers mongodb-aggregation delete-file

More Programming Guides

Other Guides

More Programming Examples