python 讀寫壓縮文件

  • 2019 年 10 月 10 日
  • 筆記

gzip 讀寫 gz

bz2 讀寫 bz2

gzip compression

import gzip with gzip.open('somefile.gz', 'rt') as f: text = f.read()

bz2 compression

import bz2 with bz2.open('somefile.bz2', 'rt') as f: text = f.read(

gzip compression

import gzip with gzip.open('somefile.gz', 'wt') as f: f.write(text)

bz2 compression

import bz2 with bz2.open('somefile.bz2', 'wt') as f: f.write(text)

compresslevel

with gzip.open('somefile.gz', 'wt', compresslevel=5) as f: f.write(text)