zip文件压缩解压–python批量实现

  • Post author:
  • Post category:python


zip解压缩文件以及压缩文件的实际使用方法——批量解压缩文件后批量修改文件内容然后再压缩文件;

import zipfile
import os
import shutil
import json


def unzip_file(zip_src, dst_dir):
    # 解压缩zip文件
    fz = zipfile.ZipFile(zip_src, "r")
    for file in fz.namelist():
        fz.extract(file, dst_dir)
    fz.close()


def modify_json_data(file):
    # 获取json文件数据
    dicts = {}
    with open(file, "rb") as f:
        data = json.load(f)
        for value in data:
            if "setConfig" in value:  # list中含有setConfig则存在背景设置
                # 遍历list寻找backgroundGrid
                for name in value:
                    if isinstance(name, dict):
                        if "backgroundGrid" in name.keys():
                            if name["backgroundGrid"] != 0:
                                name["backgroundGrid"] = 0   # 修改为纯色背景,0为纯色,1为网格,2为点状
                                print("modify {} backgrroudgrid to 0".format(file))
                dicts = data
                break
    os.remove(file)
    with open(file, "w") as fw:
        json.dump(dicts, fw)


def zip_file(path):
    # 压缩文件
    zip_name = path + ".zip"
    z = zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED)
    filelist = os.listdir(path)
    for file in filelist:
        filepath = path + "\\" + file
        if os.path.isfile(filepath):
            if file == "replayData.json":
                modify_json_data(filepath)
            z.write(filepath, file)  # filepath为写入的文件路径,file为保存的文件名
    z.close()


def do_batch_unzip(path):
    # 批量修改zip文件内内容后,重新压缩
    filelist = os.listdir(path)
    for file in filelist:
        filepath = path + "\\" + file
        if os.path.isfile(filepath):
            if file.endswith(".zip"):
                name = os.path.splitext(file)[0]
                dst_dir =path + "\\" + name  # 文件解压缩路径为相同
                unzip_file(filepath, dst_dir)   # 解压缩zip文件
                os.remove(filepath)  # 删除zip文件
                zip_file(dst_dir)   # 压缩文件
                shutil.rmtree(dst_dir)  # 删除文件夹
        else:
            do_batch_unzip(filepath)


if __name__ == "__main__":
    do_batch_unzip("E:\\Project\\ui\Data\\")






版权声明:本文为weixin_31315135原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。