python 解压指定目录的所有zip文件

复制代码
# -*- coding: utf-8 -*-
import sys
import time
import zipfile
import os
from datetime import datetime
from colorama import Fore, Style


def fake_progress_bar():
    total_progress = 50
    for i in range(total_progress + 1):
        time.sleep(0.01)  # 模拟解压文件所需的时间
        sys.stdout.write('\r[' + '#' * i + '-' * (total_progress - i) + ']')
        sys.stdout.flush()


def unzip_dir(directory):
    # 获取当前时间
    try:
        current_time = datetime.now()

        # 将时间格式化为字符串
        time_str = current_time.strftime("%Y%m%d%H%M%S")
        # 指定包含ZIP文件的目录
        # directory = 'data'

        # 遍历指定目录中的文件
        for filename in os.listdir(directory):
            if filename.endswith('.zip'):

                file_path = os.path.join(directory, filename)
                with zipfile.ZipFile(file_path, 'r') as zip_ref:
                    # 指定解压缩目标目录
                    extraction_path = os.path.join(directory, directory + "-" + time_str, filename)
                    os.makedirs(extraction_path.replace(".zip", ""), exist_ok=True)

                    # 使用tqdm进行进度显示

                    for info in zip_ref.infolist():
                        # 解决文件名编码问题
                        file_name = info.filename.encode('cp437').decode('gbk')
                        with zip_ref.open(info) as source, open(
                                os.path.join(extraction_path.replace(".zip", ""), file_name), 'wb') as target:
                            target.write(source.read())

                        # 调用模拟进度函数
                        fake_progress_bar()
                        print(f'解压 {filename} 到 {extraction_path.strip(".zip")}')
    except Exception as e:
        print(e)


if __name__ == '__main__':
    while True:
        source_directory = input(
            Fore.LIGHTGREEN_EX + "===== 请输入文件名称或输入 'q' 退出 =====\n:" + Style.RESET_ALL)  # 使用黄色文本
        if source_directory.lower() == 'q':
            print("已退出!")
            break
        if not os.path.exists(source_directory):
            print(Fore.RED + "源目录或目标目录不存在!!!\n" + Style.RESET_ALL)  # 使用红色文本
        else:
            print("开始解压:{}".format(source_directory))
            unzip_dir(source_directory)
            print("解压完毕!!!")

==========================================================

修改了一下!!!递归所有文件夹里面的zip

复制代码
# -*- coding: utf-8 -*-
import sys
import time
import zipfile
import os
from datetime import datetime
from colorama import Fore, Style


def fake_progress_bar():
    total_progress = 50
    for i in range(total_progress + 1):
        time.sleep(0.01)  # 模拟解压文件所需的时间
        sys.stdout.write('\r[' + '#' * i + '-' * (total_progress - i) + ']')
        sys.stdout.flush()


def unzip_dir(directory):
    try:
        # 获取当前时间
        current_time = datetime.now()

        # 将时间格式化为字符串
        time_str = current_time.strftime("%Y%m%d%H%M%S")

        # 遍历指定目录及其子目录中的所有ZIP文件
        for root, _, files in os.walk(directory):
            for filename in files:
                if filename.endswith('.zip'):
                    file_path = os.path.join(root, filename)
                    with zipfile.ZipFile(file_path, 'r') as zip_ref:
                        # 指定解压缩目标目录
                        extraction_path = os.path.join(root, filename + "-" + time_str)
                        os.makedirs(extraction_path, exist_ok=True)

                        # 使用tqdm进行进度显示
                        for info in zip_ref.infolist():
                            # 解决文件名编码问题
                            file_name = info.filename.encode('cp437').decode('gbk')
                            with zip_ref.open(info) as source, open(
                                    os.path.join(extraction_path, file_name), 'wb') as target:
                                target.write(source.read())

                            # 调用模拟进度函数
                            fake_progress_bar()
                            print(f'解压 {filename} 到 {extraction_path}')
    except Exception as e:
        print(e)


if __name__ == '__main__':
    while True:
        source_directory = input(
            Fore.LIGHTGREEN_EX + "===== 请输入文件夹路径或输入 'q' 退出 =====\n:" + Style.RESET_ALL)  # 使用黄色文本
        if source_directory.lower() == 'q':
            print("已退出!")
            break
        if not os.path.exists(source_directory):
            print(Fore.RED + "源目录或目标目录不存在!!!\n" + Style.RESET_ALL)  # 使用红色文本
        else:
            print("开始解压文件夹:{}".format(source_directory))
            unzip_dir(source_directory)
            print("解压完毕!!!")

附件为,打包好的exe,可以直接执行。(https://download.csdn.net/download/li13148023/88492399)

相关推荐
源码之家几秒前
基于Python房价预测系统 数据分析 Flask框架 爬虫 随机森林回归预测模型、链家二手房 可视化大屏 大数据毕业设计(附源码)✅
大数据·爬虫·python·随机森林·数据分析·spark·flask
SalvoGao7 分钟前
Python学习 | 怎么理解epoch?
数据结构·人工智能·python·深度学习·学习
楚疏笃1 小时前
纯Python 实现 Word 文档转换 Markdown
python·word
谅望者1 小时前
数据分析笔记08:Python编程基础-数据类型与变量
数据库·笔记·python·数据分析·概率论
mortimer1 小时前
【实战复盘】 PySide6 + PyTorch 偶发性“假死”?由多线程转多进程
pytorch·python·pyqt
清静诗意1 小时前
Django REST Framework(DRF)RESTful 最完整版实战教程
python·django·restful·drf
studytosky2 小时前
深度学习理论与实战:Pytorch基础入门
人工智能·pytorch·python·深度学习·机器学习
长不大的蜡笔小新2 小时前
手写数字识别:从零搭建神经网络
人工智能·python·tensorflow
前进的李工2 小时前
LeetCode hot100:094 二叉树的中序遍历:从递归到迭代的完整指南
python·算法·leetcode·链表·二叉树
ins_lizhiming3 小时前
在华为910B GPU服务器上运行DeepSeek-R1-0528模型
人工智能·pytorch·python·华为