一、压缩
1.备注
(1)os.walk(),会返回一个三元组。
path:文件夹本身的地址;dirNames:该文件夹中所有目录的名字列表;fileNames:该文件夹中所有文件文件名列表
(2)zip.write(filename[, arcname[, compress_type]])
filename代表文件完整路径;arcname代表需要保存的相对路径名称(\frontend\apple.txt),它意味着"apple.txt"在"frontent"目录中;compress_type代表压缩方式。
2.压缩完整代码
def compressFolder(folderPath, compressPathName):
'''
:param folderPath: 文件夹路径
:param compressPathName: 压缩包路径
:return:
'''
zip = zipfile.ZipFile(compressPathName, 'w', zipfile.ZIP_DEFLATED)
dict = {}
for path, dirNames, fileNames in os.walk(folderPath):
fpath = path.replace(folderPath, '')
for name in fileNames:
fullName = os.path.join(path, name).decode(encoding='gbk')
name = fpath + '\\' + name
zip.write(fullName, name)
zip.close()
compressFolder('D:/WebContent/assist_web', 'D:/WebContent/assist_web.zip')
源文件图
压缩包
二、解压
zip_file = zipfile.ZipFile("D:/WebContent/assist_web.zip")
zip_list = zip_file.namelist()
for f in zip_list:
zip_file.extract(f, "D:/WebContent/assist_web") # 循环解压文件到指定目录
zip_file.close()