Python脚本获取System32中DLL文件大小时抛出异常问题排查
为什么获取Windows System32文件夹DLL文件大小时会抛出FileNotFoundError?
我正在开发一个Python脚本,用于捕获Windows System32文件夹中的所有.DLL文件,可正常列出所有.dll文件,但尝试以MB为单位获取文件大小时,意外抛出FileNotFoundError异常。
问题代码
import os PATH = 'c:\\Windows\\system32\\' def System32(file_path): sys32 = os.listdir(file_path) for file in sys32: if '.dll' in file: yield file path_sys32 = System32(PATH) for size_file in path_sys32: name = size_file size = os.path.getsize(size_file) / 1000000 print(f'Name: {name} > {size:.2f} MB')
异常信息
Traceback (most recent call last): File "C:\Users\vinny\Desktop\scripts\main.py", line 15, in <module> size = os.path.getsize(size_file) / 1000000 ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen genericpath>", line 50, in getsize FileNotFoundError: [WinError 2] O sistema não pode encontrar o arquivo especificado: '69fe178f-26e7-43a9-aa7d-2b616b672dde_eventlogservice.dll'
注意事项
注意:当listdir()方法不传参数(脚本位于System32目录时),脚本可正常运行,代码如下:
import os def System32(): sys32 = os.listdir() for file in sys32: if '.dll' in file: yield file path_sys32 = System32() for size_file in path_sys32: name = size_file size = os.path.getsize(size_file) / 1000000 print(f'Name: {name} > {size:.2f} MB')
问题原因与解决方案
这不是os模块的bug,核心问题是文件路径未正确拼接:
os.listdir(PATH)返回的仅是文件名,不是完整路径。os.path.getsize()默认在脚本当前工作目录查找文件,自然找不到System32文件夹里的文件。- 当脚本放在System32目录运行时,
os.listdir()默认读取当前目录,os.path.getsize()也在当前目录查找,所以能正常执行。
修复方法1:拼接完整路径
修改代码,将文件名与原路径拼接成完整路径后再传入getsize():
import os PATH = 'c:\\Windows\\system32\\' def System32(file_path): sys32 = os.listdir(file_path) for file in sys32: if '.dll' in file: # 拼接完整文件路径 yield os.path.join(file_path, file) path_sys32 = System32(PATH) for full_path in path_sys32: # 从完整路径中提取文件名 name = os.path.basename(full_path) size = os.path.getsize(full_path) / 1000000 print(f'Name: {name} > {size:.2f} MB')
修复方法2:使用os.scandir()(更高效)
os.scandir()可以直接返回包含文件路径和属性的对象,无需手动拼接路径,效率更高:
import os PATH = 'c:\\Windows\\system32\\' def System32(file_path): with os.scandir(file_path) as entries: for entry in entries: # 只处理文件且后缀为.dll的项 if entry.is_file() and entry.name.endswith('.dll'): yield entry path_sys32 = System32(PATH) for entry in path_sys32: size = entry.stat().st_size / 1000000 print(f'Name: {entry.name} > {size:.2f} MB')
内容的提问来源于stack exchange,提问作者Vinícius Bruno
相关产品推荐
相关产品推荐

