如何使用 Windows 文件资源管理器到 select 和 return 使用 Python 的目录?

How to use Windows File Explorer to select and return a directory using Python?

我有一个脚本可以从远程网络节点上获取文件并将它们保存到远程驱动器。现在,我的脚本需要一个硬编码的目标位置,例如:

dest_path_cfg = f"G:\path\to\my\folder"

我想更新此脚本,以便用户 运行 它可以 select 他们想用来通过文件资源管理器保存文件的文件夹。我已经了解了如何使用:

import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')

打开文件资源管理器 window 到给定目录,但我不确定如何使用子进程允许用户的 selection 返回到 python脚本以便稍后可以对其进行操作。

现在我只关注 Windows 兼容性,但我想在将来添加 Mac/Linux 灵活性。

您可以使用 Python 的 Tkinter 模块,其中包含函数 filedialog.askdirectory()。这将打开标准 Windows 文件夹选择对话框。

import tkinter
from tkinter import filedialog

tkinter.Tk().withdraw() # prevents an empty tkinter window from appearing

folder_path = filedialog.askdirectory()

Tkinter Dialogs documentation