import zipfile
import os
def zip_files(files, output):
"""压缩多个文件"""
zip = zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED )
for file in files:
zip.write( file )
zip.close()
def zip_dir(path, output=None):
"""压缩指定目录"""
output = output or os.path.basename(path) + '.zip' # 压缩文件的名字
zip = zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(path):
relative_root = '' if root == path else root.replace(path, '') + os.sep # 计算文件相对路径
for filename in files:
zip.write(os.path.join(root, filename), relative_root + filename) # 文件路径 压缩文件路径(相对路径)
zip.close()
def unzip(zip_file, output=None):
"""解压zip文件"""
zip = zipfile.ZipFile(zip_file)
output = output or os.path.basename(zip_file.strip('.zip')) # 默认解压到当前目录同名文件夹中
zip.extractall(output) # 会被解压到输入的路径中
zip.close()