How to detect whether a file is readable and writable in Python?
Posted on In QABefore reading or writing a file, access should be checked first. How to detect whether a file is readable and writable in Python?
You can use the
os.access(path, mode)
library function https://docs.python.org/release/2.6.6/library/os.html#os.access like the Linux access
library function for C.
It returns True if access is allowed, False if not.
For readable and writable, you can test file path
with mode
set to:
os.R_OK
Value to include in the mode parameter of access() to test the readability of path.
os.W_OK
Value to include in the mode parameter of access() to test the writability of path.