I am writing a program which requires to get path from already open File Explorer / filedialog.
For example, I have opened some folder in File Explorer. It may downloads folder, program files folder or even desktop. Now I want to run a Python file and get the full path to the folder which is being displayed on the screen. For downloads folder, it should return C:\Users\User123\Downloads
or if Program Files folder is open, C:\Program Files
.
I tried reading,
- How to get the current file type at filedialog in tkinter
- Get full path of currently open files
- Python - How to check if a file is used by another application?
I even tried searching online. But none of them work.
I want something like,
import some_library
path = some_library.getPathFromFileDialogOpenedOnScreen()
print(path)
I am using Windows 10 - 64 bit and python 3.10
Can somebody help? Thanks in advance.
(For those who will ask "Why do you want to do this?", I am doing this for my college project!) :)
CodePudding user response:
On Windows, you can get a list of open Explorer windows using the Component Object Model (COM), like so:
from win32com import client
from urllib.parse import unquote
from pythoncom import CoInitialize
CoInitialize()
shell = client.Dispatch("Shell.Application")
for window in shell.Windows():
print("Open window:", window.LocationURL)
unquoted_path = list(shell.Windows())[-1].LocationURL[len("file:///"):]
most_recently_opened_window_path = unquote(unquoted_path)
print("Most recently opened window path:", most_recently_opened_window_path)
Output:
Open window: file:///C:/Stuff
Open window: file:///C:/Program Files
Open window: file:///C:/Users/Todd Bonzalez/Downloads
Most recently opened window path: C:/Users/Todd Bonzalez/Downloads
I'm not that familiar with COM. It appears to return a URL encoded string with file:///
prepended to it, so you'll need to first slice it, and then use urllib.parse.unquote
to get the proper path.
See: