Sub topic 3
Building paths with the / operator
This chapter assumes you can read basic Python and know what a Path object is from the earlier chapters. You should also know that a path can be relative or absolute. Here you will learn how / combines path pieces, what happens at the edges, and how to join untrusted input safely.
The basic idea
The / operator on a Path joins two path segments and returns a new Path. It uses the separator of the current operating system, so you never write "\\" or "/" by hand.
from pathlib import Path
report = Path("data") / "reports" / "2026" / "summary.csv"
print(report) # data/reports/2026/summary.csv on POSIX systemsOn Windows the same code prints data\reports\2026\summary.csv. The code is identical and only the output changes.
Joining is a string-level operation. Nothing checks whether data/reports exists, and nothing touches the disk. You can build a path to a file you plan to create later.
How the operator works
Path defines two special methods, __truediv__ and __rtruediv__. The first handles Path / x. The second handles x / Path when x does not know how to divide.
A plain str has no / operator. Python therefore falls back to the reflected method on the Path. This means a string on the left works as long as a Path is on the right.
from pathlib import Path
base = Path("project")
print(base / "src") # project/src
print("project" / Path("src")) # project/src
print(base / Path("src") / "main.py") # project/src/main.pyThe right operand can be a str or any os.PathLike object. Numbers, None, and other types raise TypeError.
Evaluation order: a common error
Python evaluates / from left to right. If the first two operands are both strings, the division happens before any Path is involved.
from pathlib import Path
try:
broken = "data" / "reports" / Path("2026")
except TypeError as exc:
print("TypeError:", exc)
fixed = Path("data") / "reports" / "2026"
print(fixed) # data/reports/2026The broken line computes "data" / "reports" first, and that fails. Start every chain with a Path, or wrap the first string in Path(...).
Alternatives to chained slashes
The operator is the usual choice, but two other forms are useful when the number of segments is not fixed.
from pathlib import Path
parts = ["data", "reports", "2026", "summary.csv"]
print(Path(*parts)) # data/reports/2026/summary.csv
print(Path("data").joinpath(*parts[1:])) # data/reports/2026/summary.csvPath(*parts) unpacks a list into the constructor. joinpath does the same job as repeated / and accepts several arguments at once. All three forms give the same result and follow the same rules for absolute segments, covered below.
Segments that contain separators
A segment may itself contain separators. Path splits and normalizes them, so these are equivalent on POSIX:
from pathlib import Path
a = Path("data") / "reports/2026"
b = Path("data") / "reports" / "2026"
print(a == b) # TrueForward slashes are safe on every platform. On Windows, Path accepts them and stores the path with backslashes. Prefer one segment per / when you can, because it reads clearly and avoids mixing styles.
Path also simplifies some redundant pieces when it builds the path:
| Expression | Result on POSIX | What happened |
|---|---|---|
| `Path("a") / "b" / "c"` | `a/b/c` | Normal join |
| `Path("a") / "b//c"` | `a/b/c` | Repeated separators collapse |
| `Path("a") / "./b"` | `a/b` | A `.` segment is dropped |
| `Path("a") / ""` | `a` | An empty segment adds nothing |
| `Path("a") / ".." / "b"` | `a/../b` | `..` is kept, not collapsed |
The last row matters. Path does not resolve .. while joining, because a might be a symbolic link and a/.. is not always the parent of a on disk. To collapse .. you must use resolve(), which is covered in a later chapter.
Absolute segments replace everything before them
This is the most important edge case. If the right operand is an absolute path, the result is that absolute path. The earlier segments are discarded.
from pathlib import Path
print(Path("a") / "/etc") # /etcThe same rule applies in the middle of a chain.
from pathlib import Path
print(Path("uploads") / "/etc" / "passwd") # /etc/passwdThe design follows how a shell resolves paths. A path that starts at the root does not depend on where you started. It is also a security risk when a segment comes from a user, a file name in an archive, or a web request.
On Windows there are extra cases. A segment with a different drive, such as "D:/x", replaces the whole path. A segment with a drive but no root, such as "D:x", is relative to that drive's current directory. A segment with a root but no drive, such as "/x", keeps the drive of the left side and replaces the rest.
Joining untrusted input safely
To keep a result inside a base directory, build the path, resolve it, and check that it is still under the base. Path.is_relative_to (Python 3.9 and later) does the check.
from pathlib import Path
def safe_join(base: Path, untrusted: str) -> Path:
base = base.resolve()
candidate = (base / untrusted).resolve()
if not candidate.is_relative_to(base):
raise ValueError(f"{untrusted!r} escapes {base}")
return candidate
root = Path("/srv/app/uploads")
print(safe_join(root, "photos/cat.jpg")) # /srv/app/uploads/photos/cat.jpg
for bad in ("/etc/passwd", "../secret.txt"):
try:
safe_join(root, bad)
except ValueError as exc:
print("rejected:", exc)This works because resolve() turns the candidate into an absolute path with .. collapsed and symbolic links followed. If the candidate no longer starts with the base, the input escaped. The function assumes a POSIX layout. On Windows, change the root to a path such as Path("C:/srv/app/uploads").
Anchoring paths to your script
A common use of / is to locate data files next to the code instead of relative to the current working directory. The working directory depends on how the program is launched, but __file__ does not.
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
CONFIG = BASE_DIR / "config" / "settings.toml"
print(CONFIG)This pattern runs as a saved script. It will fail in an interactive session, because __file__ is not defined there.
Joining does not change the left side
A Path is immutable. base / "x" creates a new object and leaves base unchanged. A common mistake is to write the join and ignore the result.
from pathlib import Path
base = Path("logs")
base / "today.log" # result thrown away
print(base) # logs
today = base / "today.log" # keep the new path
print(today) # logs/today.logBecause paths are immutable, they can be used as dictionary keys and set members. Paths that compare equal also hash equally.
Summary of rules
- Start a chain with a
Path, or wrap the first string inPath(...). - Each
/returns a newPath. The file system is not touched. - An absolute right operand replaces everything to its left.
..is kept as written until you callresolve().- Check untrusted segments before joining, or use a function like
safe_join.
Exercise
What does each line print on a POSIX system, or does it raise an error? (a) print(Path("x") / "y" / "z.txt") (b) print("x" / "y" / Path("z.txt")) (c) print(Path("x") / "/y" / "z.txt")
Show answer
(a) prints x/y/z.txt. (b) raises TypeError, because "x" / "y" is evaluated first and two strings cannot be divided. (c) prints /y/z.txt, because the absolute segment /y discards x.
Exercise
A web handler receives a file name from the user and runs Path("/srv/files") / name. Name two inputs that would let the user read a file outside /srv/files, and describe how to fix the handler.
Show answer
The inputs /etc/passwd (an absolute segment replaces the base) and ../../etc/passwd (.. segments climb out of the base) both escape. Fix it by resolving the joined path and rejecting it unless candidate.is_relative_to(base.resolve()) is true, as safe_join does above.