Modern File Paths with pathlib
Published by Brayan K
For years Python developers juggled file paths as fragile strings with os.path. pathlib replaced all of that with clean Path objects that know how to join, search, read, and write. It's the modern standard, and once you use it you won't go back.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A path is an object, not a string
Text in quotes is only text. Python doesn't know that "reports" is a folder, and / between two strings means division, which text can't do:
folder = "reports"
print(folder / "2024.csv")
# ✅ Expected error:
# TypeError: unsupported operand type(s) for /: 'str' and 'str'pathlib gives paths their own type, on which / joins the parts. The first half of this lesson uses PurePosixPath, a path that is only worked out and never looked up on the disk, so the examples print the same on every computer. Path, which the second half uses for real files, joins and splits paths in exactly the same way and adds the methods that read and write.
from pathlib import PurePosixPath
folder = PurePosixPath("reports")
print(folder / "2024" / "q1.csv")
print("reports" / PurePosixPath("q1.csv"))
print(folder / "2024/q1.csv")
print(folder.joinpath("2024", "q1.csv"))
# ✅ Expected output:
# reports/2024/q1.csv
# reports/q1.csv
# reports/2024/q1.csv
# reports/2024/q1.csvText on one side of / is fine as long as the other side is a path, a part can hold several folders, and joinpath() is the same join as a method. A path is not equal to its text, though. Compare it with another path, or turn it into text with str():
from pathlib import PurePosixPath
p = PurePosixPath("reports") / "q1.csv"
print(p == "reports/q1.csv")
print(str(p) == "reports/q1.csv")
print(p == PurePosixPath("reports/q1.csv"))
print(p.suffix == ".csv", str(p).endswith(".csv"))
# ✅ Expected output:
# False
# True
# True
# True TrueText methods don't exist on a path: PurePosixPath("report.csv").endswith(".csv") stops with AttributeError: 'PurePosixPath' object has no attribute 'endswith', so ask for the .suffix or call str() first. Gluing with + fails too, with TypeError: unsupported operand type(s) for +: 'PurePosixPath' and 'str'.
The os.path functions build the same paths as plain text, joined with the separator of the computer the program runs on. Modules and Packages covers the os module.
An absolute part starts the path over
/ does more than glue text. A part that starts with / is an absolute path, counted from the top of the disk, and the join starts over from it. Double slashes and . folders are tidied away, but .. is left alone, because pathlib doesn't look at the disk to see where it leads:
from pathlib import PurePosixPath
base = PurePosixPath("reports")
print(base / "2024" / "q1.csv")
print(base / "/2024" / "q1.csv")
print(PurePosixPath("a//b/./c"), PurePosixPath("a/../b"))
# ✅ Expected output:
# reports/2024/q1.csv
# /2024/q1.csv
# a/b/c a/../bSo a slash at the start of a name someone typed in can send a file somewhere else entirely.
name, stem, suffix and parent
A path hands out each part of its name. repr() shows the quotes, so an empty part is easy to spot:
from pathlib import PurePosixPath
for name in ["archive.tar.gz", ".bashrc", "notes", "photo.JPG", "v1.2.txt"]:
p = PurePosixPath(name)
print(repr(p.name), repr(p.stem), repr(p.suffix), p.suffixes)
# ✅ Expected output:
# 'archive.tar.gz' 'archive.tar' '.gz' ['.tar', '.gz']
# '.bashrc' '.bashrc' '' []
# 'notes' 'notes' '' []
# 'photo.JPG' 'photo' '.JPG' ['.JPG']
# 'v1.2.txt' 'v1.2' '.txt' ['.2', '.txt'].suffix is only the last dot onwards and .suffixes lists them all. .stem is the name without its last suffix. A leading dot alone doesn't start a suffix: .bashrc has none, while .config.json has .json. A suffix keeps its capitals, so compare p.suffix.lower() when the case might vary.
The with_ methods give a new path with one part changed. Like string methods, they leave the original as it was:
from pathlib import PurePosixPath
p = PurePosixPath("exports/2024/sales.csv")
print(p.with_suffix(".json"))
print(p.with_name("summary.txt"))
print(p.with_stem("sales-final"))
print(p.with_suffix(""))
print(PurePosixPath("archive.tar.gz").with_suffix(".zip"))
print(p)
# ✅ Expected output:
# exports/2024/sales.json
# exports/2024/summary.txt
# exports/2024/sales-final.csv
# exports/2024/sales
# archive.tar.zip
# exports/2024/sales.csvA new suffix needs its dot:
from pathlib import PurePosixPath
p = PurePosixPath("exports/2024/sales.csv")
print(p.with_suffix("json"))
# ✅ Expected error:
# ValueError: Invalid suffix 'json'.parent is the folder a path is in, and .parents every folder above it, the nearest first. relative_to() gives the rest of a path below a folder:
from pathlib import PurePosixPath
p = PurePosixPath("/home/ada/docs/cv.pdf")
print(p.parent)
print([str(folder) for folder in p.parents])
print(PurePosixPath("cv.pdf").parent)
print(p.relative_to("/home/ada"))
print(p.is_relative_to("/srv"))
# ✅ Expected output:
# /home/ada/docs
# ['/home/ada/docs', '/home/ada', '/home', '/']
# .
# docs/cv.pdf
# FalseA name on its own has ., the current folder, as its parent. relative_to() a folder the path isn't inside stops with a ValueError, whose wording changed in Python 3.12, so ask is_relative_to() first.
Windows paths
On Windows, Path joins with backslashes and knows about drives. PureWindowsPath does the same on any computer, which shows the difference here:
from pathlib import PurePosixPath, PureWindowsPath
print(PurePosixPath("home") / "ada" / "notes.txt")
print(PureWindowsPath("C:/Users") / "ada" / "notes.txt")
w = PureWindowsPath("C:/Users/ada/notes.txt")
print(w.name, w.suffix, w.drive)
print(w.as_posix())
print(PureWindowsPath("Notes.TXT") == PureWindowsPath("notes.txt"))
print(PurePosixPath("Notes.TXT") == PurePosixPath("notes.txt"))
# ✅ Expected output:
# home/ada/notes.txt
# C:\Users\ada\notes.txt
# notes.txt .txt C:
# C:/Users/ada/notes.txt
# True
# FalseWindows paths take forward slashes too, and as_posix() turns backslashes into them. Windows also ignores capitals in names, so the Windows paths compare equal and the Linux ones don't.
Typing a Windows path with backslashes has a trap. In ordinary quotes a backslash starts an escape, so \n is a line break and \t a tab, as Regular Expressions (re) showed. A raw string keeps every backslash:
from pathlib import PureWindowsPath
print(len("C:\new\table.csv"), len(r"C:\new\table.csv"))
print(PureWindowsPath(r"C:\new\table.csv").name)
print(PureWindowsPath("C:/new/table.csv").name)
# ✅ Expected output:
# 14 16
# table.csv
# table.csvThe first text is two characters shorter: \n and \t became one character each. A \U starts a Unicode escape, so a path to a user's folder written in ordinary quotes stops the program before it runs:
print("C:\Users\ada")
# ✅ Expected error:
# SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escapeReading and writing a whole file
From here on the examples use Path with real files. Each one makes its own files in the folder it runs in, which in this site's editor starts empty. write_text() creates a file, or replaces everything in it, and read_text() returns the whole file as one string:
from pathlib import Path
note = Path("todo.txt")
print(note.exists())
note.write_text("Buy milk\nWalk the dog\n", encoding="utf-8")
print(note.exists(), note.is_file(), note.is_dir())
text = note.read_text(encoding="utf-8")
print(text.splitlines())
print(text.split("\n"))
# ✅ Expected output:
# False
# True True False
# ['Buy milk', 'Walk the dog']
# ['Buy milk', 'Walk the dog', '']The text ends with a line break, so split("\n") leaves an empty string at the end and splitlines() doesn't. Writing again replaces the file rather than adding to it:
from pathlib import Path
log = Path("log.txt")
log.write_text("first\n", encoding="utf-8")
log.write_text("second\n", encoding="utf-8")
print(log.read_text(encoding="utf-8").splitlines())
log.write_text(log.read_text(encoding="utf-8") + "third\n", encoding="utf-8")
print(log.read_text(encoding="utf-8").splitlines())
# ✅ Expected output:
# ['second']
# ['second', 'third']Reading, adding and writing back works for small files. File Handling shows open(), which can add to the end of a file without rewriting it. write_text() takes only text: write_text(42) stops with TypeError: data must be str, not int, so convert numbers with str() first.
Every read and write here passes encoding="utf-8". Without it, Python uses the computer's own default, which isn't UTF-8 on every system, so a file written on one computer can come out wrong, or not at all, on another. Reading with the wrong encoding looks like this:
from pathlib import Path
menu = Path("menu.txt")
menu.write_text("café", encoding="latin-1")
print(menu.read_text(encoding="latin-1"))
print(menu.read_text(encoding="utf-8"))
# ✅ Expected output:
# café
# ✅ Expected error:
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: unexpected end of dataLatin-1 stores é as one byte that UTF-8 can't read. Strings, Bytes & Unicode Encodings explains why.
Making folders, and files that aren't there
mkdir() makes a folder. parents=True also makes any missing folders above it, and exist_ok=True makes a second run harmless:
from pathlib import Path
logs = Path("practice") / "logs"
logs.mkdir(parents=True, exist_ok=True)
logs.mkdir(parents=True, exist_ok=True)
print(logs.is_dir(), logs.parent.is_dir())
print(logs.as_posix())
# ✅ Expected output:
# True True
# practice/logsas_posix() prints the path with forward slashes on every computer. Without parents=True, Path("practice/logs").mkdir() stops with FileNotFoundError, because practice doesn't exist yet. A second mkdir() of the same folder without exist_ok=True stops with FileExistsError, and reading a file that isn't there is a FileNotFoundError with the message No such file or directory: 'notes.txt'. These messages also carry an error number in square brackets, which is different in this site's editor, so they aren't shown as runs here.
Until Exception Handling shows how to catch the error, check first:
from pathlib import Path
notes = Path("notes.txt")
if notes.is_file():
print(notes.read_text(encoding="utf-8"))
else:
print("No notes yet:", notes.name)
# ✅ Expected output:
# No notes yet: notes.txtListing a folder: iterdir() and glob()
iterdir() gives everything in a folder, glob() what matches a pattern, and rglob() what matches in the folder and every folder below it:
from pathlib import Path
shop = Path("shop")
(shop / "2024").mkdir(parents=True)
for name in ["b.csv", "a.csv", "notes.txt", "2024/c.csv"]:
(shop / name).write_text("x", encoding="utf-8")
print(sorted(p.name for p in shop.iterdir()))
print(sorted(p.name for p in shop.glob("*.csv")))
print(sorted(p.as_posix() for p in shop.rglob("*.csv")))
print(sorted(p.name for p in shop.iterdir() if p.is_dir()))
# ✅ Expected output:
# ['2024', 'a.csv', 'b.csv', 'notes.txt']
# ['a.csv', 'b.csv']
# ['shop/2024/c.csv', 'shop/a.csv', 'shop/b.csv']
# ['2024']Always sort a listing. These methods return what they find in whatever order the file system keeps it: this site's editor lists files in the order they were made, and a Linux computer in another order. In a pattern, * matches any run of characters in a name and ? one character; Finding Files with glob & fnmatch covers patterns in full.
The default case matching of glob() depends on the platform. Make the rule explicit when the same filenames must match everywhere: compare the suffix directly for exact case, or compare its lower-case form to accept either spelling:
from pathlib import Path
inbox = Path("inbox")
inbox.mkdir()
for name in ["jan.pdf", "feb.PDF"]:
(inbox / name).write_text("x", encoding="utf-8")
print(sorted(p.name for p in inbox.iterdir() if p.suffix == ".pdf"))
print(sorted(p.name for p in inbox.iterdir() if p.suffix.lower() == ".pdf"))
# ✅ Expected output:
# ['jan.pdf']
# ['feb.PDF', 'jan.pdf']A misspelt folder isn't an error for glob(): it finds nothing.
from pathlib import Path
print(sorted(Path("reprots").glob("*.csv")))
print(Path("reprots").exists())
# ✅ Expected output:
# []
# FalseWhen a search finds nothing, check the folder with exists(). glob() also hands back an iterator, used up after one pass like those in itertools: save found = shop.glob("*.csv") for a folder with one CSV, and list(found) gives one path the first time and an empty list the second. sorted() makes a list, which you can go through as often as you like.
Renaming, moving and deleting
rename() moves a file to a new path and returns that path. Give it a bare name and the file goes to the folder the program runs in, not the folder it was in:
from pathlib import Path
drafts = Path("drafts")
drafts.mkdir()
old = drafts / "report.txt"
old.write_text("x", encoding="utf-8")
moved = old.rename("final.txt")
print(moved.as_posix(), moved.exists())
print(sorted(p.name for p in drafts.iterdir()))
# ✅ Expected output:
# final.txt True
# []To rename a file where it is, build the new path from the old one:
from pathlib import Path
drafts = Path("drafts")
drafts.mkdir()
old = drafts / "report.txt"
old.write_text("x", encoding="utf-8")
renamed = old.rename(old.with_name("final.txt"))
print(renamed.as_posix(), old.exists())
print(sorted(p.name for p in drafts.iterdir()))
# ✅ Expected output:
# drafts/final.txt False
# ['final.txt']unlink() deletes a file, and missing_ok=True makes deleting one that's already gone harmless:
from pathlib import Path
draft = Path("draft.txt")
draft.write_text("x", encoding="utf-8")
draft.unlink()
print(draft.exists())
draft.unlink(missing_ok=True)
print("no error")
# ✅ Expected output:
# False
# no errorrmdir() removes only an empty folder. Copying files, and moving or deleting whole folders, is High-Level File Operations (shutil).
Practice: an inbox of CSV files
Fill the three blanks with the values in the hint lines, in order, so that the program finds the CSV files whatever the case of their suffix and saves their names in a summary file.
from pathlib import Path
inbox = Path("inbox")
inbox.mkdir(___=True)
for name in ["jan.CSV", "feb.csv", "notes.txt"]:
(inbox / name).write_text("month,total\n", encoding="utf-8")
csv_files = sorted(p.name for p in inbox.iterdir() if p.suffix.___() == ".csv")
print(csv_files)
summary = inbox / "summary.txt"
summary.___(", ".join(csv_files), encoding="utf-8")
print(summary.read_text(encoding="utf-8"))
print(summary.with_suffix(".md").name)
# 👉 replace ___ with exist_ok
# 👉 replace ___ with lower
# 👉 replace ___ with write_text
# ✅ Expected output:
# ['feb.csv', 'jan.CSV']
# feb.csv, jan.CSV
# summary.mdOn your own: sort a downloads folder
Start with these lines, which make a downloads folder holding four files:
from pathlib import Path
messy = Path("downloads")
messy.mkdir(exist_ok=True)
for name in ["photo.jpg", "report.pdf", "song.mp3", "mystery.xyz"]:
(messy / name).write_text("x", encoding="utf-8")Move each file into a folder inside downloads named after its type: Images for .jpg, Documents for .pdf, Audio for .mp3 and Other for anything else. Go through the files in name order and print a line such as moved photo.jpg -> Images for each, then print the sorted names of the folders. A dictionary from suffix to folder name, read with get() and a default, does the sorting. Then compare with this solution:
from pathlib import Path
messy = Path("downloads")
messy.mkdir(exist_ok=True)
for name in ["photo.jpg", "report.pdf", "song.mp3", "mystery.xyz"]:
(messy / name).write_text("x", encoding="utf-8")
buckets = {".jpg": "Images", ".pdf": "Documents", ".mp3": "Audio"}
for item in sorted(messy.iterdir()):
if not item.is_file():
continue
folder = messy / buckets.get(item.suffix.lower(), "Other")
folder.mkdir(exist_ok=True)
item.rename(folder / item.name)
print("moved", item.name, "->", folder.name)
print(sorted(p.name for p in messy.iterdir() if p.is_dir()))
# ✅ Expected output:
# moved mystery.xyz -> Other
# moved photo.jpg -> Images
# moved report.pdf -> Documents
# moved song.mp3 -> Audio
# ['Audio', 'Documents', 'Images', 'Other']sorted(messy.iterdir()) makes the list of files before any folder is made, so the loop never meets the new folders, and is_file() would skip them if it did. Renaming to folder / item.name keeps each file's name in its new folder.
Practice quiz
p = PurePosixPath("backup/archive.tar.gz"). What are p.suffix and p.stem?
- .tar.gz and archive
- .gz and archive.tar
- .gz and archive
- gz and archive.tar
Answer: .gz and archive.tar. suffix is only the last dot onwards, and stem is the name without it. suffixes gives ['.tar', '.gz'].
What does PurePosixPath("reports") / "/2024" / "q1.csv" give?
- /2024/q1.csv
- reports/2024/q1.csv
- reports//2024/q1.csv
- An error
Answer: /2024/q1.csv. "/2024" is an absolute path, so the join starts over from it and drops reports.
folder = "reports", then print(folder / "q1.csv"). What happens?
- reports/q1.csv
- reportsq1.csv
- reports\q1.csv
- It stops with TypeError: unsupported operand type(s) for /: 'str' and 'str'
Answer: It stops with TypeError: unsupported operand type(s) for /: 'str' and 'str'. Both sides are text, and / between two strings means division. Make one side a path.
What does PurePosixPath("reports/q1.csv") == "reports/q1.csv" give?
- False
- True
- An error
- None
Answer: False. A path is not equal to its text. Compare with str(p), or with another path.
What does PurePosixPath("sales.csv").with_suffix("json") do?
- It gives sales.json
- It gives salesjson
- It stops with ValueError: Invalid suffix 'json'
- It gives sales.csv.json
Answer: It stops with ValueError: Invalid suffix 'json'. A suffix must start with its dot: with_suffix(".json").
A folder holds jan.pdf and feb.PDF. What does sorted(p.name for p in folder.iterdir() if p.suffix == ".pdf") give?
- ['feb.PDF', 'jan.pdf']
- ['jan.pdf']
- []
- ['jan.pdf', 'feb.PDF']
Answer: ['jan.pdf']. String comparison matches capital letters exactly on every platform. Compare p.suffix.lower() to accept either case.
drafts holds report.txt. After (drafts / "report.txt").rename("final.txt"), what are Path("final.txt").exists() and (drafts / "final.txt").exists()?
- False and True
- True and True
- An error
- True and False
Answer: True and False. A bare name in rename() is relative to the working directory, so the file left drafts. rename(old.with_name("final.txt")) keeps it there.
shop holds one CSV file. found = shop.glob("*.csv"), then print(len(list(found)), len(list(found))). What prints?
- 1 1
- 0 0
- 1 0
- It stops with TypeError
Answer: 1 0. glob() hands back an iterator, which the first list() uses up.
Continue this course
- Previous: itertools
- Next: Checkpoint: A Real-World Script — Combine APIs, dates, regex and CSV into one real script — then a quiz
- Quick reference: Python cheat sheet › Files & with
Frequently asked questions
My program says FileNotFoundError, but the file is right there. Why?
A relative path such as data.csv is looked up from the folder the program runs in, its working directory, not from the folder the script is saved in. Run the script from its own folder, or build the path from the script's location: Path(__file__).parent / "data.csv". __file__ doesn't exist in this site's editor, which runs your code without a script file.
Where do files go in this site's editor?
Into a folder in the browser's memory, /home/pyodide. Before each Run, the editor deletes what earlier Runs wrote there (apart from names starting with a dot), so every Run starts as a program does in a new, empty folder, and everything is gone once you leave the page. On your own computer, files stay until you delete them: there, running a mkdir() without exist_ok=True a second time stops with FileExistsError.
How do I go through every folder below one?
rglob("*") lists everything below a folder, at any depth. Python 3.12 added Path.walk(), which goes folder by folder like os.walk(); this site's editor runs Python 3.11, which doesn't have it yet.