Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if I have permission to create folders at path in Python3?

I am creating an application with python 3 using tkinter. My application gathers data from physical devices and needs to store this on the harddrive. The program allows the user to specify a directory where they want the data to be stored. This is done with the askdirectory from tkinter.filedialog.

After the directory is selected, I need to check if the directory is 'valid'. A directory is valid if the software has permission to create new directories with arbitrary names in the specified directory. This is the part where I'm stuck.
I read on the internet that I could use os.access(path, perm) and check the permissions at path. Following is an example of the results, using a standard user without admin rights in python 3.7.0:

>>> os.access("C:\Program Files\Android", os.W_OK | os.X_OK)
True
>>> os.access("C:\Program Files\kjkjieikjd", os.W_OK | os.X_OK)
False
>>> os.access("C:\Program Files", os.W_OK | os.X_OK)
True

This is not the result that I desire, because it gives True if the given directory can be created or already exists and False otherwise. Instead I need it to return True if I can create arbitrary directories inside given directory. In the above example they should all therefore return False, because a standard user cannot create folders inside program files without admin authorisation.

I also read that I could just try to create a folder and test for exceptions using os.makedirs. This method doesn't work either, since any arbitrary directory can contain any arbitrary sub-directory and os.makedirs raises an exception when a directory already exists. In that case I would have to generate random directory names and wait until I either create the folder succesfully or I get an exception that is not FileExistsError, which is not very pretty.

Both of these methods rely on the idea that one creates a specific directory, but in my case, I need to be able to create an arbitrary directory.

How do I check if I have permission to create arbitrary directories at a given path in Python 3.7.0?

like image 853
D-Inventor Avatar asked Sep 14 '25 14:09

D-Inventor


1 Answers

There is a lot of factors (besides directory permissions) that can prevent you from creating folders and files at custom location. For example:

  • parent directory is writeable but has subdirectory (with the name you'd like to use) that is not writeable
  • disk space is low
  • UAC interrupts accessing system directories

And so on. Also take care: all these factors (including directory permissions) can change after you successfully checked the directory but before you actually wrote your data.

That's why I strongly suggest EAFP ("it's easier to ask for forgiveness than permission") approach:

  1. Try to dump your data
  2. In case of exception - handle it (and optionally delete already created files and folders)

Nevertheless, if you do need pre-checking the directory path, you can use tempfile.mkdtemp to test if any directory can be created at specified path:

def validate_path(path):
    try:
        os.makedirs(path, exist_ok=True)
        temp_dir_path = tempfile.mkdtemp(dir=path)
        os.rmdir(temp_dir_path)
        return True
    except OSError:
        return False

Or (as @Martijn Pieters proposed) a bit shorter equivalent variant using tempfile.TemporaryDirectory as a context manager:

def validate_path(path):
    try:
        os.makedirs(path, exist_ok=True)
        with tempfile.TemporaryDirectory(dir=path):
            return True
    except OSError:
        return False

Note 1: os.makedirs is nessesary, otherwise creating temporary directory will fail if path does not exist.

Note 2: if you use Python lower than 3.3, you should catch not OSError but EnvironmentError.

like image 100
Eugene Primako Avatar answered Sep 17 '25 07:09

Eugene Primako