You could just open two files, read from the gzipped
file and write to the other file (in blocks to avoid clogging the memory).
import gzip
def gunzip(source_filepath, dest_filepath, block_size=65536):
with gzip.open(source_filepath, 'rb') as s_file, \
open(dest_filepath, 'wb') as d_file:
while True:
block = s_file.read(block_size)
if not block:
break
else:
d_file.write(block)
Otherwise, you could use shutil
, as suggested in How to unzip gz file using Python:
import gzip
import shutil
def gunzip_shutil(source_filepath, dest_filepath, block_size=65536):
with gzip.open(source_filepath, 'rb') as s_file, \
open(dest_filepath, 'wb') as d_file:
shutil.copyfileobj(s_file, d_file, block_size)
Both solutions would work in Python 2 and 3.
Performance-wise, they are substantially equivalent, at least on my system:
%timeit gunzip(source_filepath, dest_filepath)
# 129 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit gunzip_shutil(source_filepath, dest_filepath)
# 132 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
https://stackoverflow.com/questions/31028815/how-to-unzip-gz-file-using-python – Anurag A S Sep 14 '18 at 13:38