Search code examples
pythontargziptarfile

How to unpack 7-Zip.gz (.gz) with Python?


I have a .tar.gz file which I want to unpack (when I unpack with 7-Zip manually, I am getting a .tar file inside). I am able to unpack this .tar file easily then with Python tarfile module then.

When I right-click the .tar.gz file in Windows Explorer, I can see under Type of file: 7-Zip.gz (.gz). I have tried using gzip module (gzip.open), however I am getting a an exception 'Not a gzipped file'. So there should be some other way to go.

I have searched the Internet and seen that people use 7-Zip manually or some batch commands, however I cannot find a way to do this in Python. I am on Python 2.7.


Solution

  • The tarfile library is able to read gzipped tar files. You should look at the examples here:

    http://docs.python.org/2/library/tarfile.html#examples

    The first example might accomplish what you want. It extracts the content of the archive to the current working directory:

    import tarfile
    tar = tarfile.open("sample.tar.gz")
    tar.extractall()
    tar.close()