Python如何获取explorer.exe激活文件夹完整路径 实现剪贴板文本存至该目录
实现方案
核心思路
不要通过资源管理器窗口标题推导路径,直接调用Windows Shell COM接口获取当前激活资源管理器窗口的真实完整路径,避免显示名称和实际路径不一致的问题。
前置依赖
安装Windows接口调用库:
pip install pywin32
核心工具函数
import win32gui import win32com.client import pythoncom import urllib.parse import os def get_active_explorer_path(): pythoncom.CoInitialize() shell = win32com.client.Dispatch("Shell.Application") # 遍历所有打开的Shell窗口(包含资源管理器和IE) for window in shell.Windows(): # 过滤出资源管理器窗口 if window.Name in ("文件资源管理器", "File Explorer"): # 匹配当前激活的窗口句柄 if window.HWND == win32gui.GetForegroundWindow(): # 提取路径,处理file协议的编码问题 url = window.LocationURL if not url.startswith("file:///"): # 虚拟路径比如此电脑、回收站,无法写入 return None # 解码转成Windows本地路径 path = urllib.parse.unquote(url[8:]).replace("/", "\\") return path return None
整合后完整代码
import win32gui import win32com.client import pythoncom import urllib.parse import os # 你原来的依赖库自行保留,比如获取剪贴板、模拟按键的库 def get_active_explorer_path(): pythoncom.CoInitialize() shell = win32com.client.Dispatch("Shell.Application") for window in shell.Windows(): if window.Name in ("文件资源管理器", "File Explorer"): if window.HWND == win32gui.GetForegroundWindow(): url = window.LocationURL if not url.startswith("file:///"): return None path = urllib.parse.unquote(url[8:]).replace("/", "\\") return path return None # 你原来的逻辑 returnValue = getClipboardData() activeWindow = getActiveWindowName() openWindowIsFolder = False target_dir = None if activeWindow == "explorer.exe": target_dir = get_active_explorer_path() openWindowIsFolder = target_dir is not None if type(returnValue) == str: if openWindowIsFolder: # 拼接保存路径 save_path = os.path.join(target_dir, "saveHere.txt") # 写入文件,用utf-8编码避免中文乱码 with open(save_path, "w", encoding="utf-8") as f: f.write(returnValue) print(f"文件已保存到{save_path}") else: pressCtrlV()
可选优化
如果要避免重名覆盖,可以给文件名加时间戳,示例如下:
from datetime import datetime timestamp = datetime.now().strftime("%Y%m%d%H%M%S") save_path = os.path.join(target_dir, f"剪贴板内容_{timestamp}.txt")
内容的提问来源于stack exchange,提问作者Bilgehan Kalay
相关产品推荐
相关产品推荐

