多層解壓p

该文章介绍了一个Python函数,用于解压7z,ZIP,RAR,TAR等格式的压缩文件,支持解压密码,同时使用tqdm库实时显示解压进度。函数还提供遍历目录的功能,递归解压所有压缩文件。
摘要由CSDN通过智能技术生成
import os
import subprocess
from tqdm import tqdm
def extract_compressed_file(file_path, password=None, extract_path="."):
    """
    解压单个压缩文件到指定目录,并实时显示解压进度
    Parameters:
    - file_path (str): 压缩文件的完整路径
    - password (str): 解压密码,默认为None
    - extract_path (str): 解压文件的目标路径,默认为当前目录
    """
    try:
        command = ["7z", "x", file_path, f"-o{extract_path}"]
        if password:
            command.append(f"-p{password}")
        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        pbar = tqdm(total=os.path.getsize(file_path), unit='B', unit_scale=True, desc=f"解压 {os.path.basename(file_path)}")
        for line in process.stdout:
            pbar.update(len(line))
        process.wait()
        pbar.close()
        if process.returncode == 0:
            print(f"成功解压:{file_path}")
            print(f"解压返回路径:{extract_path}")
            return extract_path  # 返回解压后的路径
        else:
            error_output = process.stderr.read().decode('utf-8')
            print(f"解压失败:{file_path}")
            print(f"错误信息:{error_output}")
            return None
    except Exception as e:
        print(f"解压失败:{file_path}, 错误:{e}")
        return None
def find_and_extract_compressed_files(root_dir, password=None):
    """
    遍历目录及子目录,解压所有压缩文件
    (支持7z, ZIP, RAR, XZ, BZIP2, GZIP, TAR, WIM格式,请自行在下面file.endswith('.xx')新增自己需要的格式)
    
    注意:伪装成其他格式的压缩文件也可以解压,请确认是压缩文件就行,比如最近论坛的部分压缩文件以pdf结尾伪装,
    所以可以加上file.endswith('.pdf')以解压缩
    Parameters:
    - root_dir (str): 要遍历的根目录路径
    - password (str): 解压密码,默认为None
    """
    for root, dirs, files in os.walk(root_dir):
        initial_dir = root
        for file in files:
            if file.endswith('.7z') or file.endswith('.rar') or file.endswith('.zip') or file.endswith('.tar') or file.endswith('.pdf'):
                file_path = os.path.join(root, file)
                extract_path = os.path.splitext(file_path)[0]
                last_extracted_path = extract_compressed_file(file_path, password=password, extract_path=extract_path)
                if last_extracted_path:
                    find_and_extract_compressed_files(last_extracted_path, password=password)
if __name__ == "__main__":
    root_directory = input("请输入要遍历的目录路径: ")
    password = input("请输入解压密码(如果没有密码,请直接按回车键): ")
    if password.strip() == "":
        password = None
    find_and_extract_compressed_files(root_directory, password)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值