压缩数据创建gzip文件
先看一个略麻烦的做法
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()
Copy after login
但其实有个快捷的封装,不用用到StringIO模块
f = gzip.open('file.gz', 'wb')
f.write(content)
f.close()
Copy after login
压缩已经存在的文件
python2.7后,可以用with语句
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)
Copy after login
如果不考虑跨平台,只在linux平台,下面这种方式更直接
from subprocess import check_call
check_call('gzip /path/to/file',shell=True)
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
-
2025-02-26 03:58:14
-
2025-02-26 03:38:10
-
2025-02-26 03:17:10
-
2025-02-26 02:49:09
-
2025-02-26 01:08:13
-
2025-02-26 00:46:10
-
2025-02-25 23:42:08
-
2025-02-25 22:50:13
-
2025-02-25 21:54:11
-
2025-02-25 20:45:11
Latest Issues
-
2025-03-26 16:39:41
-
2025-03-26 16:38:35
-
2025-03-26 16:37:42
-
2025-03-26 16:36:43
-
2025-03-26 16:35:41