Python Pathlib Basics
A Path is an object that holds the path of a file or folder. Parts join to a Path with the / sign.
Joining paths as strings
This path is built from plain strings. Every slash is typed as text.
folder = "notes"
path = folder + "/" + "2026" + "/" + "todo.txt"
print(path)Make a Path
Path comes from the pathlib module. Give it a name as a string.
from pathlib import Path
photo = Path("holiday.jpg")
print(photo)Join with /
The / sign joins parts into one path. No string joining is needed.
from pathlib import Path
path = Path("notes") / "2026" / "todo.txt"
print(path)Read the parts
Three properties read the file name in pieces. A suffix is the ending of a name, like .txt.
from pathlib import Path
path = Path("notes") / "todo.txt"
print(path.name)
print(path.stem)
print(path.suffix)Go to the parent
The parent is the folder that holds the path. You can ask for the parent of a parent.
from pathlib import Path
path = Path("notes") / "2026" / "todo.txt"
print(path.parent)
print(path.parent.parent)Folders on your machine
These two calls find real folders on your machine. Their values differ per computer, so this lesson does not print them.
from pathlib import Path
here = Path.cwd()
home = Path.home()Example
from pathlib import Path
report = Path("notes") / "2026" / "report.txt"
print(report)
print("Name:", report.name)
print("Stem:", report.stem)
print("Suffix:", report.suffix)
print("Parent:", report.parent)Key points
- Path: an object that holds the path of a file or folder
- Use / to join a Path to a name or to another Path
- Use .name to get the full name, with its ending
- Use .stem to get the name without the ending
- Use .suffix to get the ending, like .txt
- Use .parent to get the folder that holds the path
- Use Path.cwd() to get the folder you are working in
- Use Path.home() to get your home folder
In this example, one Path is built from three parts with the / sign. The full path prints first. The name is the last part, with its ending. The stem is the name without the ending. The suffix is the ending alone. The parent is the folder part of the path.
Note
A Path prints with / on Linux and Mac.
Windows prints it with a backslash instead.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does Path("notes") / "todo.txt" give you?