This article describes how to use the gzip module to compress files in Python. the examples in this article are mainly for UNIXZ systems. For more information, see
Create a gzip file with compressed data
First look at a slightly troublesome practice
Import StringIO, gzipcontent = 'Life is short. I use python 'zbuf = StringIO. stringIO () zfile = gzip. gzipFile (mode = 'WB ', compresslevel = 9, fileobj = zbuf) zfile. write (content) zfile. close ()
However, there is a fast encapsulation, and the StringIO module is not used.
F = gzip.open('file.gz ', 'wb') f. write (content) f. close ()
Compress existing files
After python2.7, you can use the with statement.
Import gzipwith 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 the linux platform, the following method is more direct:
From subprocess import check_callcheck_call ('gzip/path/to/file', shell = True)