You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取已打开文件资源管理器的目录路径并批量移动文件

获取已打开文件管理器的目录路径并批量移动文件

不同操作系统的文件管理器实现逻辑不同,以下是对应平台的Python解决方案:

Windows 平台

依赖pywin32库,先执行pip install pywin32完成安装。通过Windows API枚举资源管理器窗口,提取窗口标题对应的目录路径(需过滤"快速访问"这类非路径标题):

import win32gui
import re

def get_explorer_paths():
    paths = set()
    def enum_windows_callback(hwnd, _):
        window_title = win32gui.GetWindowText(hwnd)
        if not window_title:
            return
        # 判断是否为资源管理器窗口
        class_name = win32gui.GetClassName(hwnd)
        if class_name in ("CabinetWClass", "ExploreWClass"):
            # 过滤非路径类标题
            if re.match(r"^[A-Za-z]:\\", window_title) or window_title.startswith("//"):
                paths.add(window_title)
    win32gui.EnumWindows(enum_windows_callback, None)
    return list(paths)

# 获取已打开的资源管理器路径
explorer_paths = get_explorer_paths()

macOS 平台

依赖pyobjc库,执行pip install pyobjc安装。借助AppKit框架访问Finder窗口,提取当前显示的目录路径:

from AppKit import NSWorkspace

def get_finder_paths():
    paths = set()
    workspace = NSWorkspace.sharedWorkspace()
    finder_app = workspace.applicationWithBundleIdentifier_("com.apple.finder")
    if not finder_app:
        return []
    for window in finder_app.windows():
        target_url = window.target().url()
        if target_url:
            paths.add(target_url.path())
    return list(paths)

# 获取已打开的Finder路径
finder_paths = get_finder_paths()

Linux 平台(以GNOME Nautilus为例)

需要系统安装xdotool(通过apt install xdotool等包管理器)和Python库dbus-python(pip install dbus-python)。通过DBus接口查询Nautilus窗口的当前目录:

import dbus

def get_nautilus_paths():
    paths = set()
    try:
        bus = dbus.SessionBus()
        nautilus_obj = bus.get_object("org.gnome.Nautilus", "/org/gnome/Nautilus")
        nautilus_iface = dbus.Interface(nautilus_obj, "org.gnome.Nautilus.Application")
        for window_path in nautilus_iface.GetWindows():
            window_obj = bus.get_object("org.gnome.Nautilus", window_path)
            window_iface = dbus.Interface(window_obj, "org.gnome.Nautilus.Window")
            location = window_iface.GetLocation()
            paths.add(location.replace("file://", ""))
    except dbus.exceptions.DBusException:
        print("Nautilus未运行或DBus连接异常")
    return list(paths)

# 获取已打开的Nautilus路径
nautilus_paths = get_nautilus_paths()

批量移动文件到目标文件夹

拿到路径后,可遍历目录下的文件并移动到指定文件夹(自动处理重复文件名):

import os
import shutil

def batch_move_files(source_dirs, target_dir):
    os.makedirs(target_dir, exist_ok=True)
    for dir_path in source_dirs:
        if not os.path.isdir(dir_path):
            continue
        for filename in os.listdir(dir_path):
            source_file = os.path.join(dir_path, filename)
            if not os.path.isfile(source_file):
                continue
            target_file = os.path.join(target_dir, filename)
            # 处理重复文件,添加计数器后缀
            if os.path.exists(target_file):
                name, ext = os.path.splitext(filename)
                counter = 1
                while os.path.exists(os.path.join(target_dir, f"{name}_{counter}{ext}")):
                    counter += 1
                target_file = os.path.join(target_dir, f"{name}_{counter}{ext}")
            shutil.move(source_file, target_file)

# 示例:Windows平台使用
# target_dir = "D:/统一存放文件夹"
# batch_move_files(explorer_paths, target_dir)

内容的提问来源于stack exchange,提问作者GM B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:05:26