An example of how to extract all the files from a compressed ".tar.gz" file using python:
Table of contents
Uncompress a tar file in python
Let's consider a compressed file called for example data.tar.gz. In python to uncompress a tar file, a solution is to use the tarfile module:
import tarfile
fname = "data.tar.gz"
if fname.endswith("tar.gz"):
tar = tarfile.open(fname, "r:gz")
tar.extractall()
tar.close()
elif fname.endswith("tar"):
tar = tarfile.open(fname, "r:")
tar.extractall()
tar.close()
A case study
For a project (that can be found here on Github), I wanted to download a compressed file from an url address and uncompress it on my local machine using python:
Download the compressed file ('modis_c6_luts.tar.gz') from the following url address:
import urllib.request
url = 'https://atmosphere-imager.gsfc.nasa.gov/sites/default/files/ModAtmo/resources/modis_c6_luts.tar.gz'
downloaded_filename = 'modis_c6_luts.tar.gz'
urllib.request.urlretrieve(url, downloaded_filename)
and uncompress it
import tarfile
fname = 'modis_c6_luts.tar.gz'
if fname.endswith("tar.gz"):
tar = tarfile.open(fname, "r:gz")
tar.extractall()
tar.close()