大家好,对Python 压缩和解压缩文件的简单示例感兴趣的小伙伴,下面一起跟随三零脚本的小编来看看Python 压缩和解压缩文件的简单示例的例子吧。
#!/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.log
ZIP_DEFLATED是压缩标志,如果使用它需要编译了zlib模块,如果仅仅是打包而不压缩的话,可以改为zipfile.ZIP_STORED
#!/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里有目录,则在当前目录下也应该存在对应的目录,否则会报错。
#!/usr/bin/python
import zipfile
import os
f = zipfile.ZipFile('archive.zip','w',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