First, get the list of all files.

files = ['/path/to/foo.txt.gz.001', '/path/to/foo.txt.gz.002', '/path/to/foo.txt.gz.003']

Then iterate over each file and append to a result file.

with open('./result.gz', 'ab') as result:  # append in binary mode
    for f in files:
        with open(f, 'rb') as tmpf:        # open in binary mode also
            result.write(tmpf.read())

Then extract is using zipfile lib. You could use tempfile to avoid handle with temporary zip file.

Answer from Mauro Baraldi on Stack Overflow
๐ŸŒ
Medium
medium.com โ€บ bright-ai โ€บ unzip-multiple-files-with-python-d3823ccfea25
Big Data: Unzip multiple .gz files with python - ProdAI - Medium
October 17, 2022 - Big Data: Unzip multiple .gz files with python Below is a code to extract multiple files in a folder and replace those with unzipped files. This works for .gz files on Mac Step 1: In a code editor โ€ฆ
Discussions

zip - Unzip gz files within folders in a main folder using python - Stack Overflow
I have searched high and low but ... option gzip -dr..... which means "decompress recursive" and will go through each folder and extract the contents to the same location while deleting the original zipped file. Does anyone know how I can use python to loop through folders within a folder, find any zipped files and unzip them to the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
linux - How to unzip multiple gz files in python using multi threading? - Stack Overflow
I have multiple gz files with a total size of around 120GB. I want to unzip(gzip) those files to the same directory and remove the existing gz file. Currently we are doing it manually and it is taking more time to unzip using gzip -d . Is there a way I can unzip those files in parallel by creating a python ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to unzip a massive amount of files using Windows Python 2.7?

Why over engineer? Simply gunzip -r a directory of zipped files:

gunzip -r ./directory_of_zipped_files/

EDIT: Sorry ... now noted that you said windows. This is a *nix solution.

More on reddit.com
๐ŸŒ r/learnpython
17
13
June 8, 2013
gzip - Unzipping multiple .gz files into single text file using Python - Stack Overflow
I am trying to unzip multiple .gz extentions files into single .txt file. All these files have json data. I tried the following code: from glob import glob import gzip for fname in glob('.../2020-... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 4, 2021
๐ŸŒ
GitHub
gist.github.com โ€บ kstreepy โ€บ a9800804c21367d5a8bde692318a18f5
For a given directory, unzip all .gz files in folder, save unzipped files in folder and deleted zipped files. A python solution for instances where you do not have access to PowerShell. ยท GitHub
For a given directory, unzip all .gz files in folder, save unzipped files in folder and deleted zipped files. A python solution for instances where you do not have access to PowerShell. - gz_extract.py
Top answer
1 of 2
11

You can do this very easily with multiprocessing Pools:

import gzip
import multiprocessing
import shutil

filenames = [
    'a.gz',
    'b.gz',
    'c.gz',
    ...
]

def uncompress(path):
    with gzip.open(path, 'rb') as src, open(path.rstrip('.gz'), 'wb') as dest:
        shutil.copyfileobj(src, dest)

with multiprocessing.Pool() as pool:
    for _ in pool.imap_unordered(uncompress, filenames, chunksize=1):
        pass

This code will spawn a few processes, and each process will extract one file at a time.

Here I've chosen chunksize=1, to avoid stalling processes if some files are bigger than average.

2 of 2
2

A large segment of of the wall clock time spent decompressing a file with gunzip or gzip -d will be from the I/O operations (reading and writing to disk). It might even be more than the time spent actually decompressing data. You can take advantage of this by having multiple gzip jobs going in the background. As some jobs are blocked on I/O, another job can actually run without having to wait in a queue.

You can speed up the decompressing of the entire file set by having multiple gunzip processes running in the background. Each serving a specific set of files.

You can whip up something easy in BASH. Split the file list into separate commands and use the & to start it as a background job. Then wait for each each job to finish.

I would recommend that you have between 2 to 2*N jobs going at once. Where N is the number of cores or logical processors on your computer. Experiment as appropriate to get the right number.

You can whip something up easy in BASH.

#!/bin/bash

argarray=( "$@" )
len=${#argarray[@]}

#declare 4 empty array sets
set1=()
set2=()
set3=()
set4=()

# enumerate over each argument passed to the script
# and round robin add it to one of the above arrays

i=0
while [ len ]
do

    if [ len ]; then
        set1+=( "${argarray[$i]}" )
        ((i++))
    fi

    if [ len ]; then
        set2+=( "${argarray[$i]}" )
        ((i++))
    fi

    if [ len ]; then
        set3+=( "${argarray[$i]}" )
        ((i++))
    fi

    if [ len ]; then
        set4+=( "${argarray[$i]}" )
        ((i++))
    fi
done

# for each array, start a background job
gzip -d ${set1[@]} &
gzip -d ${set2[@]} &
gzip -d ${set3[@]} &
gzip -d ${set4[@]} &

# wait for all jobs to finish    
wait

In the above example, I picked 4 files per job and started two separate jobs. You can easily extend the script to have more jobs, more files per process, and to take the file names as command line parameters.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to unzip a massive amount of files using windows python 2.7?
r/learnpython on Reddit: How to unzip a massive amount of files using Windows Python 2.7?
June 8, 2013 -

I have millions of zip files (.gz extension) that I need EXTRACTED. Each of the zip files has one .txt file in them and I need that .txt file to use in data analysis. Unzipping them manually would take weeks, does anyone have an easily modifiable script out there that they are willing to share? I have very little experience with Python. Thank you in advance.

Edit: should have said "Extract" instead of "unzip."

๐ŸŒ
YouTube
youtube.com โ€บ watch
How to use Python 3 to unzip / extract multiple files in a folder - YouTube
I have written a python executable script to unzip multiple tar.gz files in a directory using regular expression and os module. Enjoy !
Published ย  December 17, 2020
Find elsewhere
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ gzip.html
gzip โ€” Support for gzip files
Source code: Lib/gzip.py This module provides a simple interface to compress and decompress files just like the GNU programs gzip and gunzip would. This is an optional module. If it is missing from...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 72309709 โ€บ how-to-unzip-a-lot-of-gzip-txt-files-and-read-through-each-one
python - How to unzip a lot of gzip txt files and read through each one? - Stack Overflow
I have hundreds of files that I need analyzed. I saw somewhere that someone used this code: import glob import gzip ZIPFILES='name.gz' filelist = glob.glob(ZIPFILES) for gzfile in filelist: # print("#Starting " + gzfile) #if you want to know which file is being processed with gzip.open(gzfile, 'r') as f: for line in f: print(line)
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 42625560 โ€บ how-to-unzip-several-files
python 2.7 - How to unzip several files - Stack Overflow
If you're going to be loading data into memory and perform analysis, it may be worthwile to unzip everything first, and then ready in the numpy arrays from the extracted files. ... import os import gzip import numpy as np dirn = 'ADS2017' unzipped_dirn = 'ADS2017_unzipped' if not os.path.exists(unzipped_dirn): os.mkdir(unzipped_dirn) # Unzip files.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ converting multiple gzip files in a directory to csv
r/learnpython on Reddit: Converting multiple gzip files in a directory to csv
November 19, 2019 -

Hi All,

I am a beginner with Python trying to solve a few problems with my daily workflow in a non-tech job. I recently wrote a script that I feel could use some improvement, but I am not knowledgeable enough to know how to make it more efficient.

Background: I sometimes need to download multiple large compressed .txt.gz files from our server and convert them into .csv before I offload them to other business units for review. Instead of extracting manually and pasting into Excel, I wanted to write a script to take care of it. Here is what I came up with after some YouTube and StackOverflow searching (the delimiter in these txt files is a '|' instead of the standard ',':

import csv
import shutil
import gzip
import os

src_dir = 'C:\\Users\\user\\Downloads\\'
dest_dir = 'C:\\Users\\user\\Desktop\\Python\\extractedgzs\\'

f_names = []

# get file names
for files in os.listdir(src_dir):
    if files.endswith('.txt.gz'):
        f_names.append(files)

#file found confirmation
print('found these files:')
print(f_names)


# unzip gz file to dest dir
for name in f_names:
    with gzip.open(src_dir+name, 'rb') as f_in:
     with open(dest_dir+name[0:-6], 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

    # extracted file to .csv
    with open(dest_dir+name[0:-6], 'r') as in_file:
        stripped = (line.strip() for line in in_file)
        lines = (line.split("|") for line in stripped if line)
        with open(dest_dir+name[0:-6]+'csv', 'w', newline='') as out_file:
            writer = csv.writer(out_file)
            writer.writerows(lines)

I understand that this code is rather rigid but that it is fine since I am the only person who will ever use it and it only needs to serve this one purpose.

The main issue I have with this is that I generate an text file that is used up by the splitter/csv writer for writing the csv. I was wondering if there is any way to eliminate this step, or at the very least automate deleting that file once all the csv's are written.

I appreciate any tips you can offer!

๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ gzip
gzip โ€“ Read and write GNU zip files - Python Module of the Week
Now available for Python 3! Buy the book! ... The gzip module provides a file-like interface to GNU zip files, using zlib to compress and uncompress the data.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ bytes โ€บ how-to-unzip-a-gz-file-using-python
How to Unzip a .gz File Using Python
August 14, 2023 - This script will unzip the yourfile.gz file in the same directory. If you want to specify a different output directory, you can do so by passing it as a second argument to the gunzip function: from sh import gunzip gunzip("/path/to/yourfile.gz", "-c > /path/to/output/yourfile") The tarfile module makes it possible to read and write tar archives, including those using gzip compression.
๐ŸŒ
Jython
jython.org โ€บ jython-old-sites โ€บ docs โ€บ library โ€บ gzip.html
12.2. gzip โ€” Support for gzip files โ€” Jython v2.5.2 documentation
This module provides a simple interface to compress and decompress files just like the GNU programs gzip and gunzip would. The data compression is provided by the zlib module. The gzip module provides the GzipFile class which is modeled after Pythonโ€™s File Object.
๐ŸŒ
Xah Lee
xahlee.info โ€บ python โ€บ gzip.html
Python: Compress Decompress Gzip File
March 23, 2019 - # decompress a gzip file import gzip input = gzip.GzipFile("/Users/joe/xxtest.gz", 'rb') s = input.read() input.close() output = open("/Users/joe/xxtest", 'wb') output.write(s) output.close() print("done") Python: Get Environment Variable ยท Python: System Call ยท
๐ŸŒ
Michaelehead
michaelehead.com โ€บ 2019 โ€บ 12 โ€บ 28 โ€บ python-streaming-unzip.html
Unzipping a large gzip file in Python | Michael Head
December 28, 2019 - To showcase the power of this method for decompressing a large file without exhausting memory or disk space, I put together a repository that demonstrates the various scenarios I tried: https://github.com/headquarters/python-streaming-unzip. Here you can play around with a Docker container that can execute a Python script that attempts to decompress a gzipped file into memory, onto disk, or via the streaming method.