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
True
>>> os.access('my_folder', os.W_OK) # Check for write access
True
>>> os.access('my_folder', os.X_OK) # Check for execution access
True
>>> os.access('my_folder', os.X_OK | ox.W_OK) # Check if we can write file to the directory
True

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.

raja
Published on 22-Dec-2017 12:13:57
Advertisements