os.access
mode is F_OK (exists) or an OR of R_OK, W_OK and X_OK. access never raises for a missing path - it returns False. It checks with the REAL user id, and the answer can be stale a moment later, so for opening files the docs recommend just trying (EAFP). Available on Unix and Windows; on Windows it only sees existence and the read-only flag.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | bytes | PathLike | yes | The file or directory to test. |
| mode | int | yes | os.F_OK (0) to test existence, or R_OK (4), W_OK (2), X_OK (1) OR-ed together. |
| dir_fd | int | no (None) | Resolve a relative path against this open directory (Unix). |
| effective_ids | bool | no (False) | Check with the effective uid/gid instead of the real ones; NotImplementedError where os.supports_effective_ids does not contain os.access. |
| follow_symlinks | bool | no (True) | False tests a symlink itself. |
Return value
bool — True if every requested kind of access is allowed; False otherwise, including when the path does not exist.
Common patterns
try: f = open('config.ini') except FileNotFoundError: data = DEFAULTS except PermissionError: raise SystemExit('config.ini is not readable') else: with f: data = f.read()
import os if not os.access(out_dir, os.W_OK): print(f'warning: cannot write to {out_dir}')
import os is_exe = os.path.isfile(p) and os.access(p, os.X_OK)
Examples
Pitfalls
import os os.R_OK and os.W_OK
import os os.R_OK | os.W_OK
import os if os.access('cfg.ini', os.R_OK): data = open('cfg.ini').read() else: data = 'defaults' data
try: with open('cfg.ini') as f: data = f.read() except OSError: data = 'defaults' data
When to use
- Friendly pre-flight messages ("output folder is not writable")
- setuid programs that must check what the REAL user may do
- Finding executables (X_OK) on Unix - or use shutil.which
- Guarding open() → just open it and catch OSError
- Existence only → os.path.exists / Path.exists
- Windows ACL checks → access only sees the read-only flag
Notes
FAQ
What access() answers depends on the permissions of the machine and on who runs the code (root, for example, gets True for writing almost anything), so a live result would describe our server, not your files. The examples create their own files and only show answers that are the same on Linux and Windows.