Python (Scripting) - Determine if an file or directory is readable writable (os.access)

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
In a Python script, the os.access module can be used to determine if a file or a directory is readable and writable.
#!/usr/bin/python3
import getpass
import os
whoami = getpass.getuser()
object = "/usr/local/foo"
if os.access(object, os.R_OK):
print(f"{object} is readable by {whoami}")
else:
print(f"{object} is NOT readable by {whoami}")
if os.access(object, os.W_OK):
print(f"{object} is writeable by {whoami}")
else:
print(f"{object} is NOT writeable by {whoami}")
You will typically want to also first use os.path.exists to determine if the path exists and os.path.isfile or os.path.isdir to determine if the object is a file or is a directory.
#!/usr/bin/python3
import getpass
import os
whoami = getpass.getuser()
object = "/usr/local/foo"
if os.path.exists(object):
print(f"{object} exists"
else:
print(f"{object} does NOT exists"
if os.path.isfile(object):
print(f"{object} is a file"
else:
print(f"{object} is NOT a file"
if os.access(object, os.R_OK):
print(f"{object} is readable by {whoami}"
else:
print(f"{object} is NOT readable by {whoami}"
if os.access(object, os.W_OK):
print(f"{object} is writeable by {whoami}"
else:
print(f"{object} is NOT writeable by {whoami}"
Did you find this article helpful?
If so, consider buying me a coffee over at