Python中win32com GetFileVersion报错pywintypes.com_error求助
问题原因与解决办法
原因分析
- 路径含隐藏特殊字符:你的
file_path字符串开头存在不可见的左向右标记(LRM)字符,系统无法识别正确路径,这是复制路径时容易出现的问题,直接触发了"找不到文件"类错误(对应错误码-2147024894)。 - Scripting.FileSystemObject兼容性有限:该COM对象的
GetFileVersion方法本身对无版本资源的exe会报错,但你所有exe都出问题,核心原因还是路径问题。
解决办法
方法1:修复路径(最快解决)
手动输入文件路径,或删除路径开头的隐藏字符:
from win32com.client import Dispatch def get_version_number(file_path): information_parser = Dispatch("Scripting.FileSystemObject") version = information_parser.GetFileVersion(file_path) return version # 手动输入路径,避免复制带来的隐藏字符 file_path = r'C:\Users\Alex\Downloads\ChromeSetup.exe' version = get_version_number(file_path) print(version)
方法2:改用pywin32原生API(更可靠)
避开COM对象的局限性,直接调用Windows API获取版本信息:
import win32api import win32file def get_exe_version(file_path): try: size = win32api.GetFileVersionInfoSize(file_path) if size == 0: return "无版本信息" info = win32api.GetFileVersionInfo(file_path, "\\") ms = info['FileVersionMS'] ls = info['FileVersionLS'] return f"{win32file.HIWORD(ms)}.{win32file.LOWORD(ms)}.{win32file.HIWORD(ls)}.{win32file.LOWORD(ls)}" except Exception as e: return f"获取失败: {str(e)}" file_path = r'C:\Users\Alex\Downloads\ChromeSetup.exe' print(get_exe_version(file_path))
方法3:使用shell模块获取属性
通过win32com.shell模块读取文件属性:
from win32com.shell import shell, shellcon def get_file_version(file_path): try: file_info = shell.SHGetFileInfo(file_path, 0, shellcon.SHGFI_VERSION) version_ms = file_info[0].dwFileVersionMS version_ls = file_info[0].dwFileVersionLS return f"{version_ms >> 16}.{version_ms & 0xFFFF}.{version_ls >> 16}.{version_ls & 0xFFFF}" except Exception as e: return f"获取失败: {str(e)}" file_path = r'C:\Users\Alex\Downloads\ChromeSetup.exe' print(get_file_version(file_path))
内容的提问来源于stack exchange,提问作者Keras-JOB
相关产品推荐
相关产品推荐

