Sub topic 3
Building paths with the / operator
This chapter assumes you know basic Python syntax, functions, and loops, and that you have seen Path objects from the previous chapters. Here you will build paths by joining segments with the / operator, see what the operator accepts, and learn the one behavior that causes real bugs.
Joining segments
A Path overloads / so that it joins path segments. The result is a new Path. The original objects are never changed.
from pathlib import Path
report = Path("data") / "reports" / "2026" / "summary.csv"
print(report) # data/reports/2026/summary.csv on POSIX systemsThe operator uses the separator of the current operating system. On Windows the same code prints data\reports\2026\summary.csv. You never type a separator yourself, so the code runs on both systems.
What goes on each side
The left side or the right side must be a Path. The other side can be a plain string or another path. Once the first operand is a Path, every later / keeps producing Path objects.
from pathlib import Path
base = Path("data")
print(base / "reports") # data/reports
print("archive" / base) # archive/data
print(base / Path("2026", "q1")) # data/2026/q1Two plain strings do not work. "data" / "reports" raises a TypeError, because str does not define / for another str. At least one operand must be a Path.
A segment can also contain separators. base / "reports/2026" works, and it gives the same result as two separate joins. Separate segments are easier to read and easier to replace with variables.
Joining without the operator
The operator is the usual choice. Two other forms are useful in some situations.
Path("data", "reports", "2026")builds a path from several segments in one call.base.joinpath("reports", "2026")does the same thing as a method call on an existing path.
All three forms follow the same rules, including the one in the next section.
Absolute segments replace earlier segments
When a segment on the right is an absolute path, the join discards everything before it.
from pathlib import Path
print(Path("a") / "/etc") # /etcThis is the same rule os.path.join follows. It is useful when a value may be either relative or absolute, such as a configured directory. It is dangerous when the segment comes from a user or from a file you do not control. A name like /etc/passwd escapes the base directory you intended.
A reasonable check resolves the result and confirms that it is still under the base directory. Resolving paths is covered in a later chapter, but the pattern is short enough to preview.
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
print(safe_join(Path("uploads"), "photos/cat.png"))is_relative_to is available in Python 3.9 and later. With safe_join(Path("uploads"), "/etc/passwd"), the function raises ValueError.
How the join is evaluated
Python evaluates / from left to right. Each step produces a new Path, and the absolute-segment rule applies at each step.
Joining does not touch the file system
Building a path only creates an object. It does not check that the file exists, and it does not create anything. Path("no") / "such" / "file.txt" is a valid path even if no such directory exists. Checking the file system is the subject of a later chapter.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `"data" / "file.txt"` | `TypeError` | Start with `Path("data")` |
| `Path("data") + "/file.txt"` | `TypeError` | Use `/` |
| `Path("data") / "/file.txt"` | Result is `/file.txt` | Remove the leading slash or check the segment |
| `Path("data") / user_input` | May leave `data` | Validate with a check such as `safe_join` |
Exercise
What does Path("logs") / "app" / "/var/tmp" / "x.log" evaluate to on a POSIX system, and why?
Show answer
It evaluates to /var/tmp/x.log. The join steps give logs/app, and then the absolute segment /var/tmp discards that result. The final join adds x.log to /var/tmp.
Exercise
Why does "data" / "reports" raise a TypeError, and how do you fix it?
Show answer
Neither operand is a Path, and str does not define /. Wrap one side in Path, for example Path("data") / "reports".