A simple tutorial for compressing files using the gzip module in Python
- 2020-05-07 19:57:35
- OfStack
compresses data to create gzip files
So is going to do a little bit of a trick
import StringIO,gzip
content = 'Life is short.I use python'
zbuf = StringIO.StringIO()
zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf)
zfile.write(content)
zfile.close()
But there is a quick package that doesn't use the StringIO module
f = gzip.open('file.gz', 'wb')
f.write(content)
f.close()
compresses existing files
After python2.7, you can use the with statement
import gzip
with open("/path/to/file", 'rb') as plain_file:
with gzip.open("/path/to/file.gz", 'wb') as zip_file:
zip_file.writelines(plain_file)
If you do not consider cross-platform, only on linux platform, the following approach is more straightforward
from subprocess import check_call
check_call('gzip /path/to/file',shell=True)