Perform checks using os.access
suggest changeos.access reports whether the real user id can reach path. It is not a stronger existence test than os.path.exists. A later open can still fail: it uses the effective user id, and the permissions can change between the check and the open.
import os
path = "/home/myFiles/directory1"
## Check if path exists
os.access(path, os.F_OK)
## Check if path is readable
os.access(path, os.R_OK)
## Check if path is writable
os.access(path, os.W_OK)
## Check if path is executable
os.access(path, os.X_OK)
It is possible to perform all checks together. Combine the flags with |. There is no os.E_OK. & is wrong here: os.F_OK is 0, so & with os.F_OK collapses the mask to 0.
os.access(path, os.F_OK | os.R_OK | os.W_OK | os.X_OK)
Each call returns True or False. os.F_OK is true when the path exists. The other flags test read, write, and execute permission. The constants exist on Unix and Windows. On Windows, os.X_OK can be true for a file that is not an executable program.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents