Python中的Zip模块
2016-10-07 本文已影响0人
灵幻云
Python中的Zip模块
在之前的项目中,遇到了一种业务场景,对于分包处理的smali文件,通过Apktool 1.5版进行打包,只会识别smali文件下的smali文件,而从Dex并没有导入到最终的apk包中,需要写一个脚本重新将其余的smali文件打包成从Dex文件,然后写入到apk中,这里我使用了python中的zip模块来处理。
zipfile模块下的ZipFile类
我们可以看一下该类中的注释:
Class with methods to open, read, write, close, list zip files.
z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True)
file: Either the path to the file, or a file-like object.
If it is a path, the file will be opened and closed by ZipFile.
mode: The mode can be either read 'r', write 'w', exclusive create 'x',
or append 'a'.
compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib),
ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma).
allowZip64: if True ZipFile will create files with ZIP64 extensions when
needed, otherwise it will raise an exception when this would
be necessary.
参数 | 意义 |
---|---|
file | zip压缩文件路径 |
mode | 打开模式,其中r是读取已存在的zip文件,w表示新建一个zip或者覆盖原有zip文件,a表示将内容添加到现有的zip中 |
compression | zip文档使用的压缩方法,zipfile. ZIP_STORED、ZIP_DEFLATED、ZIP_BZIP2、ZIP_LZMA |
allowZip64 | 需要创建大的zip文件的时候最好设置成True |
获取zip文件中的信息

import zipfile
import os
# -*- coding: utf-8 -*-
# 打开压缩文件
zipFile = r'E:\Android\Android.zip'
zipTask1 = zipfile.ZipFile(zipFile,'r')
# 遍历zip压缩文件中的文件名称
for name in zipTask1.namelist():
print(name)
# 遍历zip压缩文件中的文件信息
for info in zipTask1.infolist():
print(info)
zipTask1.close()
运行结果:

创建zip文件以及添加文件
# 将一个文件写入到zip包中
zipTask2 = zipfile.ZipFile(zipFile,'a',zipfile.ZIP_DEFLATED)
fileTxt = os.path.join(r'E:\Android',r'readme.txt')
zipTask2.write(fileTxt,r'readme2.txt')
zipTask2.close()
运行结果:
我们可以到成功的将这个文件写到了该zip文件中。

解压zip文件
# 解压文件:
targetDir = r'E:\MyBlog\Python_zip'
zipTask3 = zipfile.ZipFile(zipFile,'r',zipfile.ZIP_DEFLATED)
zipTask3.extractall(targetDir)
zipTask3.close()

设置解压密码
# 设置压缩文件密码
pwd = 'ilovepython'
zipFile = r'E:\Android\Android.zip'
zipTask4 = zipfile.ZipFile(zipFile,'r',zipfile.ZIP_DEFLATED)
zipTask4.setpassword(pwd)