Sub topic 7
Checking what exists: exists, is_file, is_dir
This chapter assumes you can build a Path object and join segments with /, as covered in earlier chapters. Here you will ask the file system questions about a path. Creating a Path never touches the disk, so a path can point at something that does not exist. These checks tell you what is really there.
The three basic checks
Path objects have three methods that return a bool:
| Method | Returns True when |
|---|---|
| `exists()` | Anything exists at the path: a file, a directory, or another entry type |
| `is_file()` | The path exists and is a regular file |
| `is_dir()` | The path exists and is a directory |
is_file() and is_dir() return False for a missing path. They do not raise an error. The script below builds a small sandbox so you can run it as shown.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "docs").mkdir()
(root / "docs" / "readme.txt").write_text("hi", encoding="utf-8")
for p in [root / "docs", root / "docs" / "readme.txt", root / "missing"]:
print(p.name, p.exists(), p.is_file(), p.is_dir())The output is:
docs True False True
readme.txt True True False
missing False False FalseUse is_file() or is_dir() when the type matters. exists() alone cannot tell you whether you may safely call read_text() or iterate over a directory.
Choosing a check
Symbolic links
A symbolic link is a file system entry that points to another path. These checks follow the link and report on its target. A link whose target is missing is called a broken link. exists() returns False for a broken link, even though the link itself is on disk. To ask about the link itself, use is_symlink():
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
link = Path(tmp) / "shortcut"
link.symlink_to(Path(tmp) / "gone.txt") # target does not exist
print(link.exists()) # False
print(link.is_symlink()) # TrueCreating symlinks on Windows may need extra privileges, so this example can fail there.
Check first, or just try?
A common pattern is to check before acting:
from pathlib import Path
config = Path("settings.toml")
if config.is_file():
text = config.read_text(encoding="utf-8")
else:
text = ""This is fine for scripts and for choosing between code paths. It has a weakness. Another process can delete or create the file between your check and your next call. This gap is called a race condition, or time-of-check to time-of-use. For code where that matters, attempt the operation and handle the error:
from pathlib import Path
config = Path("settings.toml")
try:
text = config.read_text(encoding="utf-8")
except FileNotFoundError:
text = ""Python programmers call this style "easier to ask forgiveness than permission". It also handles the case where the path is a directory, because read_text() then raises IsADirectoryError (on Windows, PermissionError).
Common mistakes
- Treating
exists()as "is a file". A directory also returnsTrue. - Assuming
Falsemeans "absent".Falseonly means Python could not find the path. A broken symlink and a missing path look the same toexists(). - Checking a relative path from the wrong working directory.
Path("data").exists()depends on where the program was started. Callresolve()to see the absolute path being tested. - Using a check as a security control. A path that exists may still be unreadable or unwritable.
Exercise
What do Path("notes").exists(), Path("notes").is_file() and Path("notes").is_dir() return when notes is a directory that exists? What does exists() return for a symlink whose target has been deleted?
Show answer
They return True, False and True. For a broken symlink, exists() returns False because it follows the link to a target that is missing. is_symlink() returns True for that link.