Automate everyday tasks with Python · Lesson 2 of 14
Paths with pathlib
Build file and folder paths with pathlib.Path, take them apart with name, stem and suffix, check that they exist and create folders.
A path is the address of a file or folder, such as photos/2026/beach.jpg. Windows writes paths with backslashes (photos\2026\beach.jpg), macOS and Linux with forward slashes. The pathlib module hides that difference: you build paths from pieces and Python uses the right separator for the computer the script runs on.
Building a path
Create a Path and add pieces to it with the / operator. The parts of a path are available as attributes: name is the last part, stem is the name without its extension, suffix is the extension (with the dot) and parent is the folder that contains it. We print paths with as_posix(), which always uses forward slashes, or print just the name: a plain print(p) shows backslashes on Windows, and full paths differ on every computer.
from pathlib import Path
p = Path("projects") / "2026" / "report.final.pdf"
print(p.as_posix())
print(p.name)
print(p.stem)
print(p.suffix)
print(p.suffixes)
print(p.parent.as_posix())
print(p.parts)projects/2026/report.final.pdf
report.final.pdf
report.final
.pdf
['.final', '.pdf']
projects/2026
('projects', '2026', 'report.final.pdf')Changing part of a path
Paths do not change in place. Methods like with_suffix(), with_name() and with_stem() return a new path with one part replaced. This is how you plan a new name before renaming a file.
from pathlib import Path
photo = Path("camera") / "IMG_0042.JPEG"
print(photo.with_suffix(".jpg").as_posix())
print(photo.with_name("beach.jpg").as_posix())
print(photo.with_stem("2026-07-14_beach").as_posix())
print(photo.suffix.lower())camera/IMG_0042.jpg camera/beach.jpg camera/2026-07-14_beach.JPEG .jpeg
Does it exist?
exists() tells you whether something is there, is_file() and is_dir() tell you what it is. Checking first lets a script skip missing files instead of crashing. The example folder below contains notes.txt and a data folder with one file.
from pathlib import Path
for name in ["notes.txt", "data", "data/sales.csv", "missing.txt"]:
p = Path(name)
print(f"{name:15} exists={p.exists()} file={p.is_file()} dir={p.is_dir()}")notes.txt exists=True file=True dir=False data exists=True file=False dir=True data/sales.csv exists=True file=True dir=False missing.txt exists=False file=False dir=False
Creating folders and files
mkdir() creates a folder. parents=True also creates any missing folders above it, and exist_ok=True means "no error if it is already there", so the script can run again safely. write_text() and read_text() write and read a whole small file in one line. Without exist_ok=True, creating a folder that already exists raises FileExistsError, as the second example shows.
from pathlib import Path
out = Path("output") / "2026" / "march"
out.mkdir(parents=True, exist_ok=True)
print("folder ready:", out.is_dir())
report = out / "summary.txt"
report.write_text("All done\n", encoding="utf-8")
print(report.read_text(encoding="utf-8").strip())
print(report.relative_to("output").as_posix())folder ready: True All done 2026/march/summary.txt
from pathlib import Path
folder = Path("backup")
folder.mkdir()
try:
folder.mkdir()
except FileExistsError:
print("backup already exists")
folder.mkdir(exist_ok=True)
print("no error with exist_ok=True")backup already exists no error with exist_ok=True
On your computer, Path.home() is your user folder and Path.cwd() is the folder the script was started from. Their values are different for every person, so try them in your own terminal.
from pathlib import Path
downloads = Path.home() / "Downloads"
print(downloads) # e.g. C:\Users\anna\Downloads or /home/anna/Downloads
print(downloads.exists())
print(Path.cwd()) # the folder you started the script from✎ Exercise
For every name in names, print the path it should get: a folder named after the extension (lower case, without the dot), and the file name with a lower-case extension. Beach.JPG becomes jpg/Beach.jpg.
Hint: p.suffix.lower() gives ".jpg"; ext[1:] drops the dot. with_suffix(ext) changes the extension and .name keeps only the file name.
from pathlib import Path
names = ["Beach.JPG", "Notes.TXT", "plan.docx"]
# your code here
Expected output:
jpg/Beach.jpg txt/Notes.txt docx/plan.docx
Show a solution
from pathlib import Path
names = ["Beach.JPG", "Notes.TXT", "plan.docx"]
for name in names:
p = Path(name)
ext = p.suffix.lower()
target = Path(ext[1:]) / p.with_suffix(ext).name
print(target.as_posix())jpg/Beach.jpg txt/Notes.txt docx/plan.docx
Check yourself
1. What is Path("docs/report.final.pdf").stem?
stem removes only the last extension, so .pdf goes and report.final stays.
2. What does exist_ok=True do in mkdir()?
parents=True creates missing parents; exist_ok=True makes an existing folder not an error.
3. Why print p.as_posix() instead of p?
as_posix() gives the same text on Windows, macOS and Linux.