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)
多層解壓p
最新推荐文章于 2024-08-20 13:04:52 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)