Python Reference ยท Files, Paths and Text I/O
The pathlib module
Reference for Python's pathlib module: build paths with /, read and write files, list and search directories, check existence and take paths apart.
pathlib represents file-system paths as objects instead of strings. A Path knows how to join itself with other parts using the / operator, take itself apart (name, suffix, parent), and talk to the file system (read, write, list, delete). It uses the right separator for the operating system automatically.
Most new code uses pathlib.Path instead of string handling with os.path. The two interoperate: anything that accepts a path accepts a Path.
from pathlib import Path config = Path("settings") / "app.toml" print(config.suffix) # .toml
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Main classes and members
| Class | Use |
|---|---|
PurePath, PurePosixPath, PureWindowsPath |
Pure computation on path strings; never touch the disk. |
Path |
A concrete path for the current system (PosixPath or WindowsPath); can touch the disk. |
Building and taking apart:
| Expression | Result |
|---|---|
Path("a") / "b" / "c.txt" |
Joins parts: a/b/c.txt. A part starting with / replaces everything before it. |
p.name, p.stem, p.suffix, p.suffixes |
Last component, without suffix, last suffix, all suffixes. |
p.parent, p.parents, p.parts |
Containing folder, all ancestors, tuple of components. |
p.with_name(x), p.with_stem(x), p.with_suffix(x) |
A new path with that piece replaced (with_stem since 3.9). |
p.relative_to(base) |
Path below base; raises ValueError if p is not under it. |
p.resolve(), p.absolute(), Path.cwd(), Path.home() |
Absolute versions, current folder, home folder. |
Working with the file system:
| Method | What it does |
|---|---|
exists(), is_file(), is_dir() |
Checks; False for a missing path. |
read_text(), write_text(s), read_bytes(), write_bytes(b) |
Whole-file reading and writing. Pass encoding=. |
open(mode) |
Like the built-in open(). |
iterdir(), glob(pattern), rglob(pattern) |
List a folder, search a pattern, search recursively. |
mkdir(parents=False, exist_ok=False) |
Create a folder. |
rename(target), replace(target), unlink(missing_ok=False), rmdir() |
Move or remove (replace overwrites silently). |
stat() |
Size, timestamps and permissions. |
Raises: FileNotFoundError, FileExistsError, NotADirectoryError, PermissionError (subclasses of OSError), and ValueError for invalid combinations such as with_suffix("txt") (a suffix must start with a dot).
Usage notes
- The
/operator is the clearest way to build paths and avoids doubled or missing separators. write_text()replaces the file, like mode"w". For appending, useopen("a").iterdir()andglob()give no guaranteed order. Wrap them insorted()when order matters.glob()returns an iterator, so convert it to a list if you need to loop twice.read_text()loads the whole file. For big files, open it and iterate.- Don't build paths with
+and strings. Concatenation breaks on separators; use/orjoinpath(). with_suffix("")removes the suffix; multi-part names such asarchive.tar.gzhave two suffixes, sowith_suffixchanges only the last one.- Pure vs. concrete. Use
PurePosixPathorPureWindowsPathto manipulate paths from another operating system. - Hidden gotcha:
Path("")isPath("."), the current folder. - Python 3.12 and later add
Path.walk()(likeos.walk()), andglobin 3.13 acceptsrecurse_symlinks. Check your Python version before relying on newer methods.