14

I want to emulate the behavior of gzip -d <file.gz> within a Python script.

The compressed GZIP file is decompressed and written as a file with the same file name as the original GZIP file without the .gz extension.

file.abc.gz --> file.abc

It's not obvious how to do this using the gzip library, all the examples in the docs are for compressing data arrays, and I've not yet found a good example from research.

Edit

I've tried the below using tarfile module, but unfortunately it's not working, I think since the GZIP file wasn't created with tar.

# get the zipped file's contents list, extract the file
with tarfile.TarFile(local_zipped_filename) as tar_file:

    # list the contents, make sure we only extract the expected named file
    members = tar_file.getmembers()
    for member in members:
        if member.name == filename_unzipped:
            members_to_extract = [member]
            tar_file.extractall(path=destination_dir, members=members_to_extract)
            break   # we've extracted our file, done
halfer
  • 19,824
  • 17
  • 99
  • 186
James Adams
  • 8,448
  • 21
  • 89
  • 148

2 Answers2

20
import gzip, shutil

with gzip.open('file.abc.gz', 'r') as f_in, open('file.abc', 'wb') as f_out:
  shutil.copyfileobj(f_in, f_out)

The gzip module provides a file-like object with the decompressed content of a gzip file; the shutil module provides a convenient helper for copying content from one file-like object to another.


This is a simple inversion of an example given in the official documentation:

Example of how to GZIP compress an existing file:

import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
-2

You can use the tarfile module to what you are asking.

Example:

import tarfile
tar = tarfile.open("test.tar.gz")
tar.extractall()
tar.close()
Rakesh
  • 81,458
  • 17
  • 76
  • 113