先日は解凍方法を書いたので今回は圧縮方法について書く。ファイルの圧縮は簡単だけど、ディレクトリの圧縮は何気に面倒だった、 ちょっと無理やりっぽい感じがするけど気にしない。 >>> import os >>> import zipfile >>> >>> arcname = 'test' >>> zf = zipfile.ZipFile(arcname + '.zip', 'w') >>> zf.writestr(arcname + '/', '') >>> for s, ds, fs in os.walk(arcname): ... for d in ds: ... zf.writestr(s + '/' + d + '/', '') ... for f in fs: ... zf.write(s + '/' + f) ... >>> zf.close() ディレクトリをそのまま圧縮しよう
