2

I have a script that takes files off of remote network nodes and saves them to a remote drive. Right now, my scripts require a hard coded destination for its location, for example:

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

I would like to update this script so that a user running it could select the folder that they wanted to use to save files via File Explorer. I've seen how I can use:

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

to open a file explorer window to a given directory, but I'm not sure how to use subprocess to allow a user's selection to be returned to the python script so that it can be acted on later.

Right now I'm only looking at Windows compatibility, but I would like to add Mac/Linux flexibility in the future.

1 Answer 1

8

You can use Python's Tkinter module, which contains the function filedialog.askdirectory(). This will open the standard Windows folder selection dialog.

import tkinter
from tkinter import filedialog

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

folder_path = filedialog.askdirectory()

Tkinter Dialogs documentation

Sign up to request clarification or add additional context in comments.

3 Comments

You can also simplify this and write tkinter.Tk().withdraw().
I've tried both of these methods and I'm not seeing the file explorer window populate. My screen briefly flashes and then my code hangs up. Not sure why the file explorer isn't displaying. I'd assume that if the window is populating correctly, then it would wait for me to select a folder and hit 'ok' before trying to proceed, right?
After some tweaking, I was able to get it working. Thank you! Much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.