在进行解压 .rar 文件之前,需要进行下载外部工具包,参考以下地址:
WinRAR archiver, a powerful tool to process RAR and ZIP filesWinRAR is a Windows data compression tool that focuses on the RAR and ZIP data compression formats for all Windows users. Supports RAR, ZIP, CAB, ARJ, LZH, TAR, GZip, UUE, ISO, BZIP2, Z and 7-Ziphttps://www.rarlab.com/download.htm
具体代码:
import os
import rarfile# rar文件批量解压rarfile.UNRAR_TOOL = r"E:\PyCharm\MyProjects\MyPythonTest01\MyProject\UnRAR.exe"def extract_rar_files(base_directory):# 1.遍历目标文件以及以下的子文件for root, dirs, files in os.walk(base_directory):for filename in files:# 1.1 筛选需要进行解压的文件,并拼接路径if filename.endswith(".rar"):rar_path = os.path.join(root, filename)# 1.2 创建解压目录extract_dir = os.path.join(root, filename[:-4])os.makedirs(extract_dir, exist_ok=True)# 2.解压 RAR 文件try:with rarfile.RarFile(rar_path) as rf:rf.extractall(path=extract_dir)print(f"解压完成: {rar_path} -> {extract_dir}")except rarfile.Error as e:print(f"解压失败: {rar_path} - {e}")if __name__ == "__main__":# 包含 RAR 文件的根目录rar_file = r"C:\Users\DELL\Desktop\2025.02.21"extract_rar_files(rar_file)
以上的 rarfile.UNRAR_TOOL 后面对应的是 unrar.exe 的绝对路径,其中,unrar.exe 放在当前 .py 文件相同包下进行引用最好