Check if Directory is currently open - without additional modules!?

Hello pyRevit Friends :slight_smile:

I want to check if the folder “C:\example” is currently open in the windows explorer.
I searched the web and came across modules that would do this job, like win32gui, pywinauto, pyautogui, etc.

I never installed a module before and it seems that i can´t without admin rights. Also I don´t know how i could share the script with my team if I use additional modules.

So is there a method I can use without using an additional module, or is there a way I can install it?

Appreciate any advice! Kind regards :slight_smile:

there’s an interesting suggestion on stackoverflow to rename the directory and try for a permission error:

import os

def try_to_rename(src, dst):
    while True:
        try:
            os.rename(src, dst)
            break
        except PermissionError:
            input(f"Unable to rename {src} to {dst}. If one or both "
                   "files/folders are open, please close them. Press Enter to "
                   "continue.")
1 Like

Hello @HikoKibar and thanks for your reply!

I tried that with the following results.

I can rename a folder succesfull even if it is open:

import os

src="C:\\Print15"
dst="C:\\Print20"

try:
	os.rename(src, dst)
except:
	print "Cant rename folder"

For files, i can rename them if they are closed but not if they are open:

import os

src="C:\\Print\\xxxx.pdf"
dst="C:\\Print\\aaaa.pdf"

try:
	os.rename(src, dst)
except:
	print "Cant rename file"

It seems this method would only work for files, but not for folders!

edit:

can´t get the full code to run:

import os

src="C:\\Users\\...\\Desktop\\test60"
dst="C:\\Users\\...\\Desktop\\test80"

def try_to_rename(src, dst):
    while True:
        try:
            os.rename(src, dst)
            break
        except PermissionError:
            input("Unable to rename src to dst. If one or both files/folders are open, please close them. Press Enter to continue.")

print try_to_rename(src, dst)
**IronPython Traceback:**
Traceback (most recent call last):
File "C:\Users\...\OneDrive - AFRY\Desktop\Share\AFRY.extension\AFRY.tab\AFRY.panel\Develop.pushbutton\Develop_script.py", line 14, in <module>
File "C:\Users\...\OneDrive - AFRY\Desktop\Share\AFRY.extension\AFRY.tab\AFRY.panel\Develop.pushbutton\Develop_script.py", line 9, in try_to_rename
NameError: global name 'PermissionError' is not defined

**Script Executor Traceback:**
IronPython.Runtime.UnboundNameException: global name 'PermissionError' is not defined

A workaround would be to try to close the explorer window “C:\example”, but this is also not possible without additional modules.

Anyway, i managed to install python, pip and the pywinauto module, so I should get this working. Just don´t know how i can later share my code with my team members.