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