Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to decompress a GZIP file to an uncompressed file on disk?

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
like image 392
James Adams Avatar asked Jan 26 '18 17:01

James Adams


1 Answers

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)
like image 87
Charles Duffy Avatar answered Sep 30 '22 02:09

Charles Duffy