Sub topic 7
Checking what exists: exists, is_file, is_dir
This chapter assumes you can build a Path with the / operator and that you know the difference between pure and concrete paths. Until now, most operations only manipulated text. The methods in this chapter ask the operating system about a path, so they belong to concrete paths (Path, not PurePath).
Paths are claims, not facts
A Path object does not guarantee that anything exists at that location. Path("data/report.csv") is a description of a place. The file may be there, may have been deleted, or may never have existed. Three methods turn that description into a question for the file system:
exists()returnsTrueif anything is at the path.is_file()returnsTrueif the path is a regular file.is_dir()returnsTrueif the path is a directory.
Each returns a bool and never changes anything on disk. The example below builds a small tree in a temporary directory so you can run it as shown.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
base = Path(tmp)
(base / "docs").mkdir()
(base / "docs" / "readme.txt").write_text("hi\n", encoding="utf-8")
for name in ["docs", "docs/readme.txt", "docs/missing.txt"]:
p = base / name
print(f"{name:17} exists={p.exists()!s:5} is_file={p.is_file()!s:5} is_dir={p.is_dir()}")
# docs exists=True is_file=False is_dir=True
# docs/readme.txt exists=True is_file=True is_dir=False
# docs/missing.txt exists=False is_file=False is_dir=FalseThe results follow a pattern you can rely on:
| Situation | `exists()` | `is_file()` | `is_dir()` |
|---|---|---|---|
| Regular file | True | True | False |
| Directory | True | False | True |
| Nothing at the path | False | False | False |
| Socket, device, or named pipe | True | False | False |
The last row matters. exists() being true does not mean is_file() or is_dir() is true. If you need to handle "something unusual is here", test for it instead of assuming a file.
Choosing the right check
Use the most specific method that matches what you are about to do. If your next step is to read a file, is_file() states your requirement exactly. exists() alone would also accept a directory, and reading it would fail later with a less helpful error.
The same flow as a reusable function:
from pathlib import Path
def describe(path: Path) -> str:
if not path.exists():
return "missing"
if path.is_dir():
return "directory"
if path.is_file():
return "file"
return "other"
print(describe(Path("."))) # directory
print(describe(Path("no_such_thing"))) # missingQuiet failures: False does not always mean "absent"
is_file() and is_dir() return False for a missing path, and they also return False when the path points at the wrong type. A False alone therefore cannot tell you why. When the reason matters, check exists() first, as describe() does above.
These methods also return False for several lookup errors, not only a missing entry:
- A component in the middle of the path is a file, not a directory. For example,
Path("notes.txt/child")wherenotes.txtis a regular file. - A path that contains a null character (this is reported as
False, not as an exception). - A symbolic link loop.
Permission problems behave differently. If Python cannot inspect a path because a parent directory denies access, exists() and the related methods can raise PermissionError instead of returning False. Do not assume these calls never raise.
Symbolic links
By default the three checks follow symbolic links. They describe the target, not the link. A link to a deleted file is called a dangling link. It reports exists() as False even though the link itself is on disk. Use is_symlink() to ask about the link itself.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
base = Path(tmp)
target = base / "data.txt"
target.write_text("x", encoding="utf-8")
link = base / "link.txt"
link.symlink_to(target) # may need extra privileges on Windows
print(link.exists(), link.is_symlink()) # True True
target.unlink()
print(link.exists(), link.is_symlink()) # False TrueIn Python 3.12 and later, exists() accepts follow_symlinks=False, which makes it report on the link itself. Python 3.13 adds the same parameter to is_file() and is_dir(). On older versions, combine is_symlink() with the other checks.
Surprises with specific path values
Two values catch people out.
First, an empty string produces the current directory, not an empty path:
from pathlib import Path
p = Path("")
print(p) # .
print(p.exists()) # True
print(p.is_dir()) # TrueIf a configuration value is missing and you pass "" to Path, a check such as Path(value).exists() succeeds for the wrong reason. Test the string itself before converting it.
Second, trailing slashes are dropped when you construct the path. Path("logs/") is the same as Path("logs"), so you cannot use a trailing slash to demand a directory. Call is_dir() instead.
Case rules also come from the operating system, not from pathlib. On a case-insensitive file system (the default on Windows and macOS), Path("README.md").exists() can be True when the real name is readme.md. Code that passes on your laptop can fail on a Linux server for this reason.
Check, then act: a race condition
A common pattern looks like this:
from pathlib import Path
path = Path("settings.json")
if path.exists():
text = path.read_text(encoding="utf-8") # may still failBetween the check and the read, another process can delete or replace the file. This gap is called a time-of-check to time-of-use (TOCTOU) race. In a short script you run alone, the risk is small. In servers, build tools, and anything that runs concurrently, it is real. The check also does not cover other failures, such as a permission error or a path that is a directory.
The more reliable approach is to perform the operation and handle the failure:
from pathlib import Path
def read_settings(path: Path) -> str:
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return "{}"
except IsADirectoryError:
raise ValueError(f"{path} is a directory, expected a file")Python programmers call this style EAFP ("easier to ask forgiveness than permission"). The upfront-check style is LBYL ("look before you leap"). Use the rule that fits the situation:
| Use a check (`exists`, `is_file`, `is_dir`) when | Use try/except when |
|---|---|
| You only need an answer, such as listing what is present | The next step is an action that can fail anyway |
| You validate user input before starting long work | Other programs may change the file system at the same time |
| You choose between two code paths, such as "use cache or build it" | You need to know which error occurred |
Some methods already contain the safe version of the check. mkdir(exist_ok=True) and unlink(missing_ok=True) replace the pattern "if it is not there, create it" and "if it is there, delete it". You will use both in later chapters.
Validating input early
Checks are well suited to rejecting bad input before you do expensive work. The function below turns a vague failure into a specific message:
from pathlib import Path
def require_file(path: Path) -> Path:
if not path.exists():
raise FileNotFoundError(f"input not found: {path}")
if path.is_dir():
raise IsADirectoryError(f"expected a file, got a directory: {path}")
if not path.is_file():
raise ValueError(f"not a regular file: {path}")
return path
try:
require_file(Path("."))
except IsADirectoryError as err:
print(err) # expected a file, got a directory: .The function keeps the three cases separate, so the caller can handle each one. It still carries the race described above, which is acceptable here because it only produces early, readable errors. The code that later opens the file should still be ready for an exception.
Common mistakes
- Using
exists()when you meanis_file()oris_dir(). A directory namedoutput.csvpassesexists(). - Reading a
Falseresult as "the path is wrong". It may be the wrong type, a permission-limited location, or a dangling link. - Checking a relative path without knowing the working directory.
Path("data").exists()depends on where the program was started. Chapter 6 covered how to make paths absolute. - Calling the checks on pure paths.
PurePathhas noexists(),is_file(), oris_dir(), because it never touches the file system. - Skipping error handling after a successful check, which leaves the race open.
Exercise
A script runs Path(user_value).is_dir() where user_value is an empty string. The check returns True. Why, and how would you fix the script?
Show answer
Path("") is converted to Path("."), the current directory, which is a directory, so is_dir() returns True. Fix it by validating the raw string before building the path, for example if not user_value: raise ValueError("path is required").
Exercise
You need to load config.toml if it exists and fall back to defaults if it does not, in a program where another process may delete the file at any time. Should you use if path.exists(): followed by read_text()? What do you do instead?
Show answer
No. The file can disappear between the check and the read, so read_text() can still raise FileNotFoundError. Call read_text() inside a try block and catch FileNotFoundError to return the defaults. Also catch IsADirectoryError if the path might be a directory.
Exercise
A symbolic link latest points to a file that was deleted. What do Path("latest").exists() and Path("latest").is_symlink() return?
Show answer
exists() returns False because it follows the link to a missing target. is_symlink() returns True because the link itself is still on disk.