CodeBlanks Logo Icon CodeBlanks

/ operator

Learn path joining with Path / 'sub'.

Joining paths with the slash

The most elegant feature of pathlib is the / operator. You can join two Path objects or a Path with a string using /: Path("folder") / "sub" / "file.txt". This replaces os.path.join.

The operator is platform-independent: it joins with a forward slash on Linux and a backslash on Windows. You write the same code on both systems. It's more readable than using strings for path joining and reduces the risk of mistakes.

Multiple joins

You can use several / in one expression: Path("a") / "b" / "c" / "d.txt". The operation goes left to right; each step produces a new Path object.

This is especially handy for structural folder hierarchies: project / "src" / "utils" / "helper.py". The old approach was os.path.join("a", "b", "c"); the / operator is far more readable.

Practice Join three parts and print the name

Start with from pathlib import Path. Join three parts with p = Path("projects") / "web" / "report.pdf". Print the filename with print(p.name).

Starter code

main.py
# Import the Path class
# Join three parts with /
# Print the filename

Sample solution

main.py
# Import the Path class
from pathlib import Path
# Join three parts with /
p = Path("projects") / "web" / "report.pdf"
# Print the filename
print(p.name)

Expected output

report.pdf

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Join with the slash operator

Question
from pathlib import Path
p = Path("docs")____ "sub"
print(p)
Answer
from pathlib import Path
p = Path("docs")/ "sub"
print(p)

Explanation: The / operator joins paths.

2 What is the result of Path("a") / "b"?

  • The string "a/b"
  • A list
  • A new Path object Correct answer
  • An error is raised

Explanation: The / operator returns a Path object again, suitable for chaining.

3 Match the path-joining concepts

Term Meaning
/ Path-joining operator
Path Path object class
name Filename attribute
parent Parent folder attribute

All lessons in Intermediate