Sub topic 7
Working with paths using pathlib
This chapter covers how pathlib represents file locations, how to build and take apart paths, and how to ask the filesystem about them. It assumes you can use open() with a with block and understand str values and try/except. Python 3.9 or newer is assumed for with_stem() and is_relative_to().
Why paths should be objects
A path is often written as a plain string such as "data/reports/2024.csv". String paths work until you need to join pieces, find the extension, or run the same code on Windows and Linux. Then you end up with code like this:
folder = "data"
name = "report.csv"
path = folder + "/" + name # breaks on Windows-style paths
extension = name.split(".")[-1] # breaks for names with no dotThe pathlib module wraps a path in an object. The object knows the rules of the operating system, so you join and inspect paths with methods and operators instead of string surgery.
from pathlib import Path
path = Path("data") / "report.csv"
print(path.suffix)Path objects work anywhere Python accepts a path, including open(). Under the hood they are immutable. Every operation that "changes" a path returns a new object.
Pure paths and concrete paths
pathlib has two families of classes.
- Pure paths (
PurePath,PurePosixPath,PureWindowsPath) only manipulate names. They never touch the disk. - Concrete paths (
Path,PosixPath,WindowsPath) add methods that talk to the filesystem, such asexists(),mkdir()anditerdir().
When you write Path(...), Python gives you a PosixPath or a WindowsPath depending on the system you run on.
Use a pure class when you want to handle a path from another system. For example, you might parse a Windows path on a Linux server, or write tests whose output must not depend on the machine. The examples below use PurePosixPath where the printed result needs to be the same everywhere.
Building paths
The / operator joins a path with a string or another path. joinpath() does the same thing with several arguments.
from pathlib import Path
base = Path("data")
report = base / "reports" / "summary.final.csv"
same = base.joinpath("reports", "summary.final.csv")
print(report == same)
print(Path.cwd()) # current working directory
print(Path.home()) # the user's home directoryTwo details cause most joining bugs:
- The left side of
/must be aPathor the right side must be aPath."data" / "x"fails because two plain strings do not support/. - If the right side is an absolute path, it replaces everything on the left.
from pathlib import PurePosixPath
print(PurePosixPath("data") / "/etc" / "hosts")This prints /etc/hosts, and data is discarded. That behavior is correct, but it surprises people when the right-hand value comes from user input.
Taking a path apart
A path object exposes its pieces as attributes. None of these touch the disk.
from pathlib import Path
p = Path("data") / "reports" / "summary.final.csv"
print(p.name)
print(p.stem)
print(p.suffix)
print(p.suffixes)
print(p.parent)
print(p.parts)On any system this prints the following values, with the separator in p.parent being a backslash on Windows:
| Attribute | Value | Meaning |
|---|---|---|
| `p.name` | `summary.final.csv` | Final component, including extension |
| `p.stem` | `summary.final` | Name without the last suffix |
| `p.suffix` | `.csv` | Last extension, with its dot |
| `p.suffixes` | `['.final', '.csv']` | Every extension in the name |
| `p.parent` | `data/reports` | The path without its last component |
| `p.parts` | `('data', 'reports', 'summary.final.csv')` | Tuple of components |
Two more attributes are worth knowing. p.parents is a sequence of all ancestors, so p.parents[0] equals p.parent. p.anchor is the root part, such as / on Linux or C:\ on Windows, and it is an empty string for a relative path.
Be careful with multi-part extensions. For archive.tar.gz, suffix is .gz and stem is archive.tar. Use suffixes if you need the whole .tar.gz. A name that starts with a dot, such as .gitignore, has an empty suffix, because Python treats the leading dot as part of the name.
Deriving new paths
Since paths are immutable, you build variations with with_* methods.
from pathlib import PurePosixPath
p = PurePosixPath("data/reports/summary.csv")
print(p.with_suffix(".json"))
print(p.with_name("totals.csv"))
print(p.with_stem("final"))
print(p.relative_to("data"))
print(p.is_relative_to("other"))The output is:
data/reports/summary.json
data/reports/totals.csv
data/reports/final.csv
reports/summary.csv
FalseSome rules to remember:
with_suffix()replaces only the last suffix. Pass an empty string to remove it.with_suffix()raisesValueErrorif the new suffix does not start with a dot, sowith_suffix("json")fails.with_name()andwith_stem()raiseValueErrorif the path has no name to replace, such asPath("/").relative_to()raisesValueErrorif the path is not under the given base. Useis_relative_to()first when you do not know.
Absolute, relative and resolved paths
A relative path depends on the current working directory, which can change while the program runs. For paths that must stay fixed, convert them early.
p.absolute()prepends the current directory without cleaning anything up.p.resolve()makes the path absolute, removes.and..components and follows symbolic links.p.expanduser()replaces a leading~with the home directory.
from pathlib import Path
print(Path("demo/../demo/notes.txt").resolve())
print(Path("~/notes.txt").expanduser())Path("~/notes.txt") on its own is a relative path whose first component is literally ~. Python never expands it unless you call expanduser().
resolve() works on paths that do not exist yet. The missing part is kept as written and only the existing part is resolved. Pass strict=True if you want a FileNotFoundError instead.
A common pattern is to anchor data files to the script rather than to the working directory:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
CONFIG = BASE_DIR / "config.json"Asking the filesystem
Concrete paths can check what is on disk.
from pathlib import Path
p = Path("demo") / "notes.txt"
print(p.exists())
print(p.is_file())
print(p.is_dir())exists() returns False for a missing path and also for a path you are not allowed to inspect in some cases. For a real file, stat() returns size and timestamps:
info = p.stat()
print(info.st_size, info.st_mtime)Creating directories and listing contents
mkdir() creates one directory. Two keyword arguments cover the usual needs:
parents=Truecreates missing ancestors, likemkdir -p.exist_ok=Truedoes not raise if the directory already exists.
Without exist_ok, a second call raises FileExistsError. Without parents, a missing parent raises FileNotFoundError.
This example builds a small tree and then reads it back:
from pathlib import Path
root = Path("demo")
(root / "logs" / "2024").mkdir(parents=True, exist_ok=True)
(root / "logs" / "2024" / "app.log").touch()
(root / "logs" / "readme.txt").touch()
(root / "notes.txt").touch()
for child in sorted(root.iterdir()):
print(child, "dir" if child.is_dir() else "file")
for log in sorted(root.rglob("*.log")):
print(log)On Linux or macOS it prints:
demo/logs dir
demo/notes.txt file
demo/logs/2024/app.logiterdir() yields the direct children, in no guaranteed order, which is why the example sorts them. glob("*.txt") matches names in one directory. rglob("*.log") is shorthand for glob("**/*.log") and searches all subdirectories. Both return generators, so wrap them in list() if you need to count or reuse the results.
Matching is case-sensitive on Linux and case-insensitive on Windows by default. If your code must behave the same on both, normalise the case yourself.
Using paths with open()
A Path can be passed straight to open(). It also has its own open() method with the same arguments.
from pathlib import Path
path = Path("demo") / "notes.txt"
with path.open("a", encoding="utf-8") as f:
f.write("one more line\n")If a library only accepts strings, convert with str(path). Another option is os.fspath(path), which returns the string form for a Path and leaves a str unchanged.
For the one-call read_text() and write_text() helpers, see the next chapter.
Common mistakes
- Joining with
+.Path("a") + "b"raisesTypeError. Use/. - Using
str.replace()for extensions."a.csv.bak".replace(".csv", ".json")changes the wrong part. Usewith_suffix(). - Forgetting that
mkdir()is not recursive by default. Passparents=True. - Assuming
~is expanded. Callexpanduser(). - Hard-coding
\or/inside strings. Pass each component to/and letpathlibpick the separator. - Comparing a relative path with an absolute one.
Path("a.txt") == Path("a.txt").resolve()isFalse. Resolve both sides first.
Exercise
A function receives a user-supplied filename name and must return the path uploads/<name> as a resolved path, raising ValueError if the result lies outside the uploads directory. Write the function and say why Path("uploads") / name alone is not enough.
Show answer
```python is not allowed inside an answer fence, so here is the code in prose form. Define base = Path("uploads").resolve(). Compute target = (base / name).resolve(). If not target.isrelativeto(base), raise ValueError("path escapes uploads"). Otherwise return target. Joining alone is not enough because name may be absolute, such as /etc/passwd, which replaces the base, or may contain .. components, such as ../secret.txt, which climb out of it. Resolving the joined path removes the .. parts, and isrelativeto() then confirms the result is still inside the base.
Exercise
Given p = Path("backups/db.sql.gz"), what do p.suffix, p.stem and p.suffixes return, and how would you build the path backups/db.sql.bak from p?
Show answer
p.suffix is .gz, p.stem is db.sql, and p.suffixes is ['.sql', '.gz']. Calling p.with_suffix(".bak") gives backups/db.sql.bak, because with_suffix() replaces only the last suffix.