2

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,

  1. How to get the current file type at filedialog in tkinter
  2. Get full path of currently open files
  3. 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!) :)

1 Answers1

4

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%20Files
Open window: file:///C:/Users/Todd%20Bonzalez/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:

GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • Thanks for answering! But, I am getting `pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)` – Shrirang Mahajan Jul 31 '22 at 09:19
  • 1
    I've updated my answer. Import and call `pythoncom.CoInitialize()` before using `win32com`, on a per-thread basis. – GordonAitchJay Jul 31 '22 at 10:38
  • Wow!!! That works!! Thanks for all the efforts you took! – Shrirang Mahajan Jul 31 '22 at 10:43
  • 1
    No problemo. Just keep in mind this doesn't account for when no Explorer windows are open, in which case you'd get a `IndexError: list index out of range` exception. So catch that exception or break up the line starting with `unquoted_path = ` and check `if list(shell.Windows()):` before indexing into it. Lists return `False` if they are empty. – GordonAitchJay Jul 31 '22 at 10:49
  • Ahh, yes! Got it! – Shrirang Mahajan Jul 31 '22 at 10:52