os.path.exists
exists is True for anything — file, folder, device; isfile only for regular files; isdir only for folders. They follow symlinks: a link to a missing target is not "existing", but lexists and islink still see the link itself. A checked answer can be stale a moment later; for creating or opening, just try and catch the error.
Demo
import os for f in ['README.md', 'src/app.py']: os.makedirs(os.path.dirname(f) or '.', exist_ok=True) open(f, 'w').close() [(p, os.path.exists(p), os.path.isfile(p), os.path.isdir(p)) for p in ['README.md', 'src', 'src/main.py']]
A missing path is (False, False, False) — no exception. A folder exists but is not a file. '.' and 'a/..' are folders too (os.path does not normalize, the OS resolves '..'). The empty string is never an existing path. None of the created files is a symlink, so islink would be False for all of them and lexists would equal exists.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | bytes | PathLike | int | yes | The path to check. exists also accepts an open file descriptor (3.3+). |
Return value
bool — True or False. Errors (missing path, permission problems, invalid names) give False.
Common patterns
import os text = open(path, encoding='utf-8').read() if os.path.isfile(path) else ''
try: with open(path, encoding='utf-8') as f: text = f.read() except FileNotFoundError: text = ''
import os broken = os.path.lexists(p) and not os.path.exists(p)
import os candidates = ['./app.toml', os.path.expanduser('~/.config/app.toml'), '/etc/app.toml'] config = next((c for c in candidates if os.path.isfile(c)), None)
Examples
Pitfalls
import os os.mkdir('data.csv') os.path.exists('data.csv')
import os os.mkdir('data.csv') os.path.isfile('data.csv')
import os if not os.path.exists('out'): os.mkdir('out') os.path.isdir('out')
import os os.makedirs('out', exist_ok=True) os.path.isdir('out')
When to use
- Branching on what kind of thing a path is
- Filtering listdir results (join the name with the folder first)
- Guarding open/create/delete → just do it and catch FileNotFoundError / FileExistsError
- pathlib code → Path.exists() / is_file() / is_dir() / is_symlink()
- Size or time → getsize / getmtime / os.stat
Notes
FAQ
os.path.isfile(path) — True only for an existing regular file. os.path.exists(path) is also True for folders. With pathlib: Path(path).is_file().