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 (unzipped) file.
gzip.open() function has the following arguments:
filenamespecifies the name of the GZipped file.
'rt'opens the file in reading (
'r') text (
't') mode (not binary mode)
newline=''prevents adding a blank line in some OS environments.
🐍 You don’t need to install the
gzip module because it’s already part of Python’s standard library. 🐍
Here’s the code to read and load a GZipped CSV to Python:
import gzip with gzip.open('my_file.csv.gz', 'rt', newline='') as csv_file: csv_data = csv_file.read() with open('my_file.csv', 'wt') as out_file: out_file.write(csv_data)
💡 Note: Depending on the .csv.gz file’s encoding, you may want to pass
utf-16', or your specific file encoding into
gzip.open() to prevent any encoding/decoding errors.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.