Sub topic 9
Creating and listing directories
This chapter covers making directories with Path.mkdir() and listing their contents with Path.iterdir(). It assumes you can build paths with /, take them apart, and check them with exists(), is_file() and is_dir(). It also assumes you can read and write small files with read_text() and write_text().
What you will be able to do
- Create one directory or a whole chain of nested directories.
- Choose between
parentsandexist_okand know what each one changes. - List the direct children of a directory and filter them by type.
- Make listings deterministic, since the order is not guaranteed.
- Recognize the errors these calls raise.
Creating a directory with mkdir
Path.mkdir() creates the directory the path points to. By default it is strict. It fails if the parent is missing, and it fails if the path already exists.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
target = base / "a" / "b"
try:
target.mkdir()
except FileNotFoundError:
print("parent 'a' does not exist yet")
target.mkdir(parents=True)
print(target.is_dir()) # True
try:
target.mkdir()
except FileExistsError:
print("b already exists")The two failures are different exceptions:
| Situation | Default behavior | Fix |
|---|---|---|
| A parent directory is missing | `FileNotFoundError` | `parents=True` |
| The path already exists | `FileExistsError` | `exist_ok=True` |
The parents argument
With parents=True, mkdir() creates every missing ancestor, like mkdir -p in a shell. Parents that already exist are left alone. The directories it creates get the default permissions, not the mode you pass.
The exist_ok argument
With exist_ok=True, mkdir() does nothing if a directory is already there. This makes setup code idempotent: you can run it twice and get the same result.
from pathlib import Path
out_dir = Path("output") / "reports"
out_dir.mkdir(parents=True, exist_ok=True)This pair of arguments is the usual way to say "make sure this directory exists".
A file in the way
exist_ok=True only forgives an existing directory. If a regular file has the same name, mkdir() still raises FileExistsError.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "data"
target.write_text("not a directory", encoding="utf-8")
try:
target.mkdir(parents=True, exist_ok=True)
except FileExistsError:
print("a file is in the way")Catching this error is often the right way to report a clear message to the user, because exist_ok=True does not make it impossible.
Setting permissions
mkdir(mode=0o750) sets the permission bits for the new directory on POSIX systems. The process umask is applied to the value, so the result can be more restrictive than what you asked for. On Windows the argument is ignored. Most scripts leave it at the default.
Why not check first?
You may be tempted to write this:
from pathlib import Path
d = Path("cache")
if not d.exists():
d.mkdir()Between the check and the call, another process can create cache, and mkdir() then raises FileExistsError. Calling d.mkdir(exist_ok=True) does the check and the creation as one step, so prefer it. It is also shorter.
Listing a directory with iterdir
Path.iterdir() yields a Path for each direct child of a directory. Each yielded path is the directory path joined with the child's name, so if the directory path is relative, the children are relative too.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "docs").mkdir()
(root / "images").mkdir()
(root / "notes.txt").write_text("todo\n", encoding="utf-8")
(root / "data.csv").write_text("a,b\n", encoding="utf-8")
for child in sorted(root.iterdir()):
kind = "dir " if child.is_dir() else "file"
print(kind, child.name)The output is:
file data.csv
dir docs
dir images
file notes.txtFour properties of iterdir() matter in practice:
- It is not recursive. Files inside
docsdo not appear. Userglob()orPath.walk()for that, which later chapters cover. - The order is arbitrary. It follows whatever the operating system returns, which can differ between machines and file systems. Wrap the call in
sorted()whenever output is displayed, saved, or compared in a test. - It includes hidden entries. A file such as
.gitignoreis listed like any other. Names are not filtered. - It is lazy. It returns an iterator, not a list. Convert it with
list()if you need to loop over it more than once or to know its length.
Errors from iterdir
Because iterdir() is lazy, the error for a bad path appears when you start iterating, not when you call it. The common cases are FileNotFoundError if the path does not exist and NotADirectoryError if it is a file. A PermissionError is raised if you cannot read the directory.
from pathlib import Path
missing = Path("does-not-exist")
try:
names = [p.name for p in missing.iterdir()]
except FileNotFoundError:
names = []
print(names) # []Checking is_dir() first is fine for friendly messages, but handle the exception too. The directory can disappear or change between the two calls.
Filtering and sorting listings
Each child is a full Path, so the methods you already know work on it. Use is_file() and is_dir() to separate the two kinds, and use suffix to narrow by extension.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "src").mkdir()
for name in ("b.py", "a.py", "notes.md", ".hidden"):
(root / name).write_text("", encoding="utf-8")
files = [p for p in root.iterdir() if p.is_file()]
visible = [p for p in files if not p.name.startswith(".")]
python_files = sorted(p.name for p in visible if p.suffix == ".py")
subdirs = sorted(p.name for p in root.iterdir() if p.is_dir())
print(python_files) # ['a.py', 'b.py']
print(subdirs) # ['src']To list directories before files, sort with a key that returns a tuple. False sorts before True, so negating is_dir() puts directories first.
from pathlib import Path
def sorted_listing(directory: Path) -> list[Path]:
return sorted(
directory.iterdir(),
key=lambda p: (not p.is_dir(), p.name.lower()),
)
for entry in sorted_listing(Path(".")):
print(entry.name + ("/" if entry.is_dir() else ""))Sorting by p.name.lower() gives a case-insensitive order. Plain sorted() on paths compares them as given, so uppercase names come before lowercase ones.
Symbolic links
is_dir() and is_file() follow symbolic links. A link that points to a directory reports True for is_dir(). A broken link reports False for both. If you need to detect links, call is_symlink() on the entry.
How listing works underneath
iterdir() reads directory entries from the operating system and builds a Path for each one. It does not open the files. Calls such as is_dir() on each entry may ask the file system again, so a filter over a very large directory costs one query per entry. For most scripts this is fine. If you profile a hot path, os.scandir() is the lower-level tool. It returns entries that carry cached type information, but you give up Path convenience.
Putting it together: a small project skeleton
This function creates a nested layout and then reports what it made. It uses only the calls from this chapter.
from pathlib import Path
import tempfile
LAYOUT = ["src/app", "tests", "docs/images"]
def create_layout(root: Path) -> list[Path]:
created = []
for relative in LAYOUT:
target = root / relative
target.mkdir(parents=True, exist_ok=True)
created.append(target)
return created
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
create_layout(root)
create_layout(root) # second run changes nothing and raises nothing
for child in sorted(root.iterdir()):
print(child.name, "->", sorted(p.name for p in child.iterdir()))The output is:
docs -> ['images']
src -> ['app']
tests -> []Running create_layout() twice works because every call uses exist_ok=True.
Common mistakes
- Forgetting
parents=Trueand gettingFileNotFoundErrorfor a nested path. - Using
exist_ok=Trueand assuming the path is a directory afterward. A file with that name still raises an error. - Relying on
iterdir()order. Tests pass on one machine and fail on another. - Expecting recursion.
iterdir()shows one level only. - Checking
exists()beforemkdir(). It adds a race condition and no benefit.
Exercise
A script runs Path("build/logs/2026").mkdir(exist_ok=True) on a machine where the build directory does not exist yet. What happens, and what single change makes the call succeed whether or not build, build/logs and build/logs/2026 already exist?
Show answer
The call raises FileNotFoundError, because existok only covers the final directory already existing and does not create missing parents. Adding parents=True fixes it: Path("build/logs/2026").mkdir(parents=True, existok=True).
Exercise
Write a function names_in(directory) that returns the names of the non-hidden regular files directly inside directory, in alphabetical order. Why must it call sorted()?
Show answer
def namesin(directory): return sorted(p.name for p in Path(directory).iterdir() if p.isfile() and not p.name.startswith(".")) It must call sorted() because iterdir() yields entries in an arbitrary, operating-system-dependent order, so the result would otherwise differ between machines and runs.