2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

gzip 圧縮されたテキストファイルを書き出す

Last updated at Posted at 2020-05-18

こんにちは。
Python で gzip 圧縮されたテキストファイルを書き出しました1

今回例は CSV データを中身としました(csv モジュール利用)。

$ ./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())
  1. 参考:"Using csv.DictWriter to output an in-memory gzipped csv file?" (Stack Overflow)

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?