LoginSignup
3
3

More than 5 years have passed since last update.

python3でcsvをgzip圧縮する方法

Posted at

をしようとしてググって出て来る情報がだいたいpython2系だったので、python3で書く方法を記録しておく。

import csv
import gzip
import io
import numpy as np

header = ["foo", "bar", "hoge"]
body = np.random.rand(3, 3)
csv_array = np.vstack([header, body])

stringio = io.StringIO()
writer = csv.writer(stringio)

writer.writerows(csv_array)

data = gzip.compress(stringio.getvalue().encode("utf-8"))
f = open("foo.csv.gz", "wb")
f.write(data)
f.close()

軽くググッた感じだとpython2系だとcsvの書き込みはstringじゃなくてbyteらしいので、もっと簡単にできるんだけど、3系は少し手間がかかる。

3
3
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
3
3