Sub topic 9
Creating and listing directories
This chapter assumes you can build paths with /, check them with exists, is_file, and is_dir, and read and write files with Path methods. It covers creating directories with mkdir and listing their contents with iterdir.
Creating a directory with mkdir
Path.mkdir() creates the directory the path points to. By default it is strict. It fails if a parent directory is missing or if the directory already exists.
| Call | Missing parent | Directory already exists |
|---|---|---|
| `mkdir()` | `FileNotFoundError` | `FileExistsError` |
| `mkdir(parents=True)` | Parents are created | `FileExistsError` |
| `mkdir(parents=True, exist_ok=True)` | Parents are created | Nothing happens |
The next example runs inside a temporary directory, so you can run it repeatedly.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
target = Path(tmp) / "project" / "data"
try:
target.mkdir()
except FileNotFoundError:
print("parent missing")
target.mkdir(parents=True)
try:
target.mkdir(parents=True)
except FileExistsError:
print("already exists")
target.mkdir(parents=True, exist_ok=True)
print(target.is_dir())The output is parent missing, already exists, and then True.
For scripts that must be safe to run twice, mkdir(parents=True, exist_ok=True) is the usual choice.
Listing a directory with iterdir
Path.iterdir() yields one Path for each entry directly inside a directory. It does not descend into subdirectories. Each yielded path already includes the parent, so entry.name gives just the final component.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "logs").mkdir()
(root / "notes.txt").write_text("hi", encoding="utf-8")
(root / "data.csv").write_text("a,b\n", encoding="utf-8")
for entry in sorted(root.iterdir()):
kind = "dir" if entry.is_dir() else "file"
print(f"{kind:4} {entry.name}")The output is:
file data.csv
dir logs
file notes.txtTwo details matter here:
iterdir()returns entries in an arbitrary order that depends on the file system. Wrap it insorted()whenever the order affects output or tests.- It includes hidden entries, such as
.giton POSIX systems, and it never yields.or...
Filtering entries
iterdir() returns files and directories together. Filter with is_dir() and is_file() in a list comprehension.
from pathlib import Path
def list_subdirs(root: Path) -> list[Path]:
return sorted(p for p in root.iterdir() if p.is_dir())
def list_files(root: Path) -> list[Path]:
return sorted(p for p in root.iterdir() if p.is_file())iterdir() raises FileNotFoundError if the directory does not exist and NotADirectoryError if the path is a file. The error is raised when iteration starts, not when you call iterdir(). A try block that wraps only the call will not catch it. Put the loop inside the try, or check is_dir() first.
Common errors
- Forgetting
parents=True. Creatinga/b/cwhenadoes not exist fails withFileNotFoundError. - Using
exist_ok=Truewithoutparents=True. The two flags are independent. The second flag does not imply the first. - Relying on listing order. Output that looks alphabetical on one machine can differ on another.
- Expecting recursion.
iterdir()shows only the top level. The next chapter coversglobandrglobfor searching whole trees.
Exercise
Write code that makes sure reports/2026/q1 exists under the current directory, then prints the names of its immediate subdirectories in alphabetical order. Which mkdir arguments do you need, and why?
Show answer
Use parents=True so reports and 2026 are created if missing, and exist_ok=True so a second run does not raise FileExistsError.
from pathlib import Path
target = Path("reports") / "2026" / "q1"
target.mkdir(parents=True, existok=True)
for p in sorted(Path("reports").iterdir()):
if p.isdir():
print(p.name)