Using df.to_csv() with the keyword argument compression='gzip' should produce a gzip archive. I tested it using same keyword arguments as you, and it worked.

You may need to upgrade pandas, as gzip was not implemented until version 0.17.1, but trying to use it on prior versions will not raise an error, and just produce a regular csv. You can determine your current version of pandas by looking at the output of pd.__version__.

Answer from root on Stack Overflow
๐ŸŒ
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!

Discussions

csv - Using csvreader against a gzipped file in Python - Stack Overflow
I have a bunch of gzipped CSV files that I'd like to open for inspection using Python's built in CSV reader. I'd like to do this without having first to manually unzip them to disk. I guess I wan... More on stackoverflow.com
๐ŸŒ stackoverflow.com
reading gzipped csv file in python 3 - Stack Overflow
I'm having problems reading from a gzipped csv file with the gzip and csv libs. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Compressing CSV to GZIP and writing to SharePoint
Hi, I'm getting errors while running this code in trying to compress a csv file to gzip and then uploading it to SharePoint using Python Code Recipe. More on community.dataiku.com
๐ŸŒ community.dataiku.com
July 19, 2022
How do I use CSV Writers with GZIP files in Python 3? - Stack Overflow
I'm trying to port some code from Python 2.7 to Python 3. The 2to3 tool works fine for the base syntax and package changes, but now we're into some strange side effects. I have the following code ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Benbarber
benbarber.co.uk โ€บ posts โ€บ using-gzip-for-storage-optimisation-in-large-csv-data-sets
Using Gzip for Storage Optimisation in Large CSV Data Sets - Ben Barber
January 24, 2023 - First, youโ€™ll need to import the gzip module and the csv module. You can do this by running the following code: ... Next, youโ€™ll need to open the gzipped CSV file. You can do this using the gzip.open() function, which works just like the built-in open() function, but automatically decompresses the file.
๐ŸŒ
Substack
dataengineeringcentral.substack.com โ€บ data engineering central โ€บ gzip. csv. python. s3. (polars vs duckdb)
Gzip. CSV. Python. S3. (Polars vs DuckDB) - by Daniel Beach
November 3, 2025 - So, IF want to use Polars, we will have to start adding more code to make this happen, maybe add some vanilla Python code to make Polars write a .csv.gz file. I guess this isnโ€™t horrible. Just two more packages. The gzip package itself doesnโ€™t support s3 paths, so we had to add s3fs/fsspec ...
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ 5 best ways to compress csv files to gzip in python
5 Best Ways to Compress CSV Files to GZIP in Python - Be on the Right Side of Change
March 1, 2024 - The resulting output is a GZIP file โ€˜data.csv.gzโ€™ that contains the compressed contents of โ€˜data.csvโ€™. This code snippet uses shutil.copyfileobj to copy the contents of an open file object to another file object. The gzip.open function is used to create the file object in binary write mode, resulting in writing a compressed file effortlessly. For systems where the UNIX gzip utility is available, Pythonโ€™s subprocess module can be used to execute a shell command.
Find elsewhere
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to convert a csv.gz to a csv in python?
How to Convert a CSV.gz to a CSV in Python? - Be on the Right Side of Change
August 10, 2022 - To convert a compressed CSV file (.csv.gz) to a CSV file (.csv) and read it in your Python shell, use the gzip.open(filename, 'rt', newline='') function call to open the gzipped file, the file.read() function to read its contents, and the file.write() function to write the CSV in a normal ...
๐ŸŒ
Opendatablend
docs.opendatablend.io โ€บ open-data-blend-datasets โ€บ loading-data-files-in-python
Loading Data Files in Python | Open Data Blend Docs
November 1, 2023 - You can use the below steps as a guide on how you can load compressed (Gzip) data files into Python. Install the pandas module from the Anaconda prompt. ... Import the pandas module. Read the compressed CSV data file into a data frame.
๐ŸŒ
Medium
medium.com โ€บ @liamwr17 โ€บ reducing-csv-file-size-with-gzip-compression-in-pandas-bfaa7c3775c6
Reducing CSV File Size with GZIP Compression in Pandas | by Liam Roberts | Medium
April 29, 2022 - Itโ€™s an extremely portable and easy to work with data format, but when you get into files with millions of rows it can start to take up a lot of space on your computer. Luckily pandas comes with an extremely easy method for reading and writing csvs to gzip which can drastically reduce your file sizes.
๐ŸŒ
DEV Community
dev.to โ€บ rijultp โ€บ the-hidden-work-behind-gzip-how-it-compresses-so-well-5ejk
The Hidden Work Behind Gzip: How it compresses so well - DEV Community
October 28, 2025 - Gzip is lossless, meaning that when you decompress it, you get back the exact original file with no changes. Compression efficiency depends on how repetitive your CSV is. Files with many repeating values compress very well. Files with random or unique data may not shrink as much. ... This restores the original data.csv file. If you want to compress or decompress CSV files in Python, the gzip module makes it simple:
๐ŸŒ
Medium
eraliod.medium.com โ€บ python-streaming-vs-batched-compression-test-4e94b51a4879
Python Streaming vs Batched Compression Test | by Damian Eralio | Medium
January 9, 2024 - import csv import gzip # new itertools ... str, csv_gz_file_path: str) -> None: """ takes an existing csv file, reads lines in batches, and writes them to an already compressed csv file ""...
๐ŸŒ
DataScientYst
datascientyst.com โ€บ read-compressed-csv-json-file-pandas
How to Read a Compressed CSV or JSON File in Pandas
February 10, 2025 - import pandas as pd df = pd.read_csv('data.csv.gz', compression='gzip') df.head() You can specify different compression types as needed: ... If the file extension matches the compression format, Pandas can automatically detect it: ```python df = pd.read_csv('data.csv.gz') # No need to specify compression
๐ŸŒ
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...
๐ŸŒ
Codegive
codegive.com โ€บ blog โ€บ pandas_read_csv_gz_file.php
Master pandas read csv gz file (2024): Unlock Compressed Data & Supercharge Your Analysis!
To read a .gz CSV file using pandas, simply pass the path to pd.read_csv(); pandas automatically detects and decompresses gzipped files. Alternatively, you can explicitly set the compression='gzip' argument for clarity.