Python脚本无法识别RAR文件求助:95个文件夹检测结果均为0
RAR文件检测脚本显示0的问题分析与解决
问题原因分析
- 路径转义错误:Windows路径中的反斜杠
\会被Python解析为转义字符,比如\I、\O可能被识别为特殊字符,导致实际访问的路径和预期不符,脚本找不到目标文件夹里的文件。 rarfile.is_rarfile()参数错误:该函数需要传入文件路径字符串,但你传入的是os.scandir()返回的DirEntry对象,函数无法正确识别文件格式。- 可能缺少UnRAR依赖:
rarfile库本身依赖系统中的UnRAR工具,如果未安装或未配置环境变量,即使文件是正常的RAR,也无法被正确识别。
解决办法
1. 修正路径写法
把路径改为原始字符串(在字符串前加r),避免转义问题:
parent_directory = r'E:\Immo_JSON' destination_directory = r'E:\OP'
2. 修正is_rarfile()的参数
将entry改为entry.path,传入正确的文件路径:
if entry.is_file() and entry.name.endswith('.rar') and rarfile.is_rarfile(entry.path):
3. 确保UnRAR工具已配置
- Windows系统:安装UnRAR工具后,将安装目录(比如
C:\Program Files\WinRAR)添加到系统环境变量的PATH中;或者在脚本里手动指定UnRAR路径:
rarfile.UNRAR_TOOL = r'C:\Program Files\WinRAR\UnRAR.exe'
修正后的完整脚本
import os import rarfile # 配置UnRAR路径(如果环境变量没配置的话) rarfile.UNRAR_TOOL = r'C:\Program Files\WinRAR\UnRAR.exe' parent_directory = r'E:\Immo_JSON' destination_directory = r'E:\OP' for folder in os.listdir(parent_directory): folder_path = os.path.join(parent_directory, folder) if os.path.isdir(folder_path): num_rar_files = 0 with os.scandir(folder_path) as entries: for entry in entries: if entry.is_file() and entry.name.endswith('.rar') and rarfile.is_rarfile(entry.path): num_rar_files += 1 print(f"{num_rar_files} .rar found in the folder {folder}")
内容的提问来源于stack exchange,提问作者Sazai
相关产品推荐
相关产品推荐

