...

Python使用zipfile模块压缩和解压缩文件及目录

压缩多个文件

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.dirname(zip_file)  # 默认解压到当前目录同名文件夹中
    zip.extractall(output)   # 会被解压到输入的路径中
    zip.close()

处理MacOS系统压缩目录生成的__MACOSX目录

def unzip_file(file_path):
    file_dir = os.path.dirname(file_path)
    new_zip_file = os.path.join(file_dir, 'new_archive.zip')
    with ZipFile(file_path) as original_zip:
        with ZipFile(new_zip_file, 'w') as new_zip:
            for item in original_zip.infolist():
                buffer = original_zip.read(item.filename)
                if not str(item.filename).startswith('__MACOSX/'):
                    new_zip.writestr(item, buffer)
            new_zip.extractall(os.path.dirname(file_path))  #解压到当前工作目录
    os.remove(new_zip_file)
    os.remove(file_path)
    return os.path.join(file_dir, os.listdir(file_dir)[0])
posted @ 2021-09-15 23:37  韩志超  阅读(4664)  评论(0编辑  收藏  举报