1,单个文件压缩成zip文件
# 来自jb51.cc
#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
f.write('1.py')
f.write('/root/install.log')
f.close()
仔细观察压缩以后的archive.zip,里面有一个1.py和一个root的目录,root目录下有一个install.logZIP_DEFLATED是压缩标志,如果使用它需要编译了zlib模块,如果仅仅是打包而不压缩的话,可以改为zipfile.ZIP_STORED
2,把zip文件解压缩
# 来自jb51.cc
#!/usr/bin/python
import zipfile
zfile = zipfile.ZipFile('archive.zip','r')
for filename in zfile.namelist():
data = zfile.read(filename)
file = open(filename,'w+b')
file.write(data)
file.close()
如果archive.zip里有目录,则在当前目录下也应该存在对应的目录,否则会报错。3,把整个文件夹压缩
# 来自jb51.cc
#!/usr/bin/python
import zipfile
import os
f = zipfile.ZipFile('archive.zip',zipfile.ZIP_DEFLATED)
startdir = "c:\\\\mydirectory"
for dirpath,dirnames,filenames in os.walk(startdir):
for filename in filenames:
f.write(os.path.join(dirpath,filename))
f.close()
如果出现:Compression requires the (missing) zlib module
解决方法:yum install zlib zlib-devel,然后重新编译安装python 原文链接:https://www.f2er.com/python/527117.html