How to check the permissions of a directory using Python?

PythonServer Side ProgrammingProgramming

You can use os.access(path, mode) to check the directory permission with modes for reading, writing and execution permissions. For being able to write you'll also need to check for execution permission. For example,

>>> import os
>>> os.access('my_folder', os.R_OK) # Check for read access
>>> os.access('my_folder', os.W_OK) # Check for write access
>>> os.access('my_folder', os.X_OK) # Check for execution access
>>> os.access('my_folder', os.X_OK | ox.W_OK) # Check if we can write file to the directory

You can also follow a common Python idiom: It's easier to ask for forgiveness than for permission. Following that idiom, you should try writing to the directory in question, and catch the error if you don't have the permission to do so.

Updated on 03-Oct-2019 05:39:04