I have a .gz file, inside which there is another file. I need to extract the file inside the zipped file.
f = gzip.open(dest, 'rb')
This only opens the file but I need to download that particular file which is inside gz instead of just opening the gz file.
This question has been marked as duplicate which I accept, but I haven't found a solution where we can actually download the file and not just read its content. Same is the case with the link mentioned.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With