[PYTHON] Export a gzip-compressed text file

Hello. I tried exporting a gzip-compressed text file in Python. This time, the content is CSV data (using csv module). "[Using csv.DictWriter to output an in-memory gzipped csv file?](Https://stackoverflow.com/questions/54559843/using-csv-dictwriter-to-output-an-in-memory-gzipped-csv- file) "(Stack Overflow) was used as a reference.

$ ./write_csv_gzfile.py temp.csv.gz
$ gzip -dc temp.csv.gz
a,b
1,2
3,4

write_csv_gzfile.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io, csv, gzip, sys
from pathlib import Path

def writeCSV(f, newline='\n'):
    dat = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
    w = csv.DictWriter(f, dat[0].keys(), lineterminator=newline)
    w.writeheader()
    w.writerows(dat)

buffer = io.BytesIO()
with gzip.GzipFile(fileobj=buffer, mode='wb') as compressed:
    with io.TextIOWrapper(compressed, encoding='utf-8', newline='\n') as wrapper:
        writeCSV(wrapper)
p = Path(sys.argv[1])
p.write_bytes(buffer.getvalue())

Recommended Posts

Export a gzip-compressed text file
Create a large text file with shellscript
Speaking Japanese with OpenJtalk (reading a text file)
Speaking Japanese with gTTS (reading a text file)
Export Python3 version OpenCV KeyPoint to a file
Convert a text file with hexadecimal values to a binary file
[Sublime Text 2] Always execute a specific file in the project
Convert HTML to text file
Upload a file to Dropbox
Read and write a file
Create a dummy data file
Write and read a file
I made a python text
Scripting Language C ——How a text file without a shebang is executed
Outputs a line containing the specified character string from a text file
Count specific strings in a file
Creating a wav file split program
Build a deb file with Docker
Write standard output to a file
Diff a binary file (image file, etc.)
Create a binary file in Python
Create a 1MByte random number file
Save a YAML-formatted file in PyYAML
How to create a config file
Create a file uploader with Django
export ENV by reading dotenv file by Shell command (set -a; source .env; set + a;) (#Shell #Linux)