Python Paths with pathlib
What you will learn
- Absolute and relative paths
- Why
pathlib.Pathbeats string tricks - Building paths with
/ - Reading the parts:
name,stem,suffix,parent - Checking, creating, reading, renaming and deleting with
Path - Typical errors
1. What is a path?
A path tells the computer where a file or folder is. There are two kinds:
| Kind | Meaning | Example |
|---|---|---|
| relative | starts from the current working folder (where the program runs) | data/sales.csv |
| absolute | starts from the top of the drive | C:\Users\Rina\data\sales.csv (Windows), /home/rina/data/sales.csv (Linux, macOS) |
Systems write paths differently: Windows separates folders with a backslash \ and has drive letters; Linux and macOS use a forward slash /. Joining paths by hand as strings ("data" + "\\" + "sales.csv") breaks when the program runs on another system. The pathlib module (standard library) solves this.
2. Path objects and the / operator
from pathlib import Path
p = Path("data") / "reports" / "2026" / "sales.csv"
print(p)
print(type(p).__name__)
data\reports\2026\sales.csv
WindowsPath
Path(...)makes a path object. The/operator joins parts (using__truediv__, lesson 13.8).- The output above is from Windows: backslashes, and the class
WindowsPath. On Linux or macOS the same code printsdata/reports/2026/sales.csvand the class isPosixPath. Your code stays the same. p.as_posix()always gives forward slashes, handy for display.
Path objects work in open(), and in most functions that expect a file name.
Quick check: what is `Path("a") / "b" / "c.txt"`?
The path a/b/c.txt (written with backslashes on Windows).
3. The parts of a path
p = Path("data") / "reports" / "2026" / "sales.csv"
print(p.name)
print(p.stem, p.suffix)
print(p.parent)
print(p.parts)
print(p.is_absolute())
sales.csv
sales .csv
data\reports\2026
('data', 'reports', '2026', 'sales.csv')
False
| Attribute | Meaning |
|---|---|
name |
the final part, sales.csv |
stem |
the name without the last extension, sales |
suffix |
the last extension, with the dot, .csv |
parent |
the folder containing it |
parts |
a tuple of every piece |
Making related paths:
print(p.with_suffix(".json"))
print(p.with_name("totals.csv"))
print(p.parent.parent.name)
print(Path("report.txt").with_stem("final"))
data\reports\2026\sales.json
data\reports\2026\totals.csv
reports
final.txt
These only build new path values; nothing happens on disk. Special cases:
print(Path("archive.tar.gz").suffixes, Path("archive.tar.gz").suffix, Path("archive.tar.gz").stem)
print(repr(Path("noext").suffix), repr(Path(".hidden").suffix), Path(".hidden").name)
['.tar', '.gz'] .gz archive.tar
'' '' .hidden
(suffix is only the last extension; suffixes lists all. A name that starts with a dot, such as .hidden, has no suffix.)
4. Does it exist?
d = Path("work")
print(d.exists(), d.is_dir())
d.mkdir()
print(d.exists(), d.is_dir(), d.is_file())
False False
True True False
exists(),is_file(),is_dir()ask about the disk.mkdir()creates a folder. If it already exists, you getFileExistsError; useexist_ok=Trueto allow it, andparents=Trueto create missing parent folders:
d.mkdir(exist_ok=True)
deep = Path("a/b/c")
deep.mkdir(parents=True, exist_ok=True)
print(deep.is_dir())
True
A path object is just a name; making one does not create anything. Path("nodir/file.txt").write_text("x") fails if nodir does not exist:
FileNotFoundError: [Errno 2] No such file or directory: 'nodir\\file.txt'
(The doubled backslash is how the error message prints a Windows path.) Create the parent folder first.
5. Reading and writing with Path
For simple cases, Path has shortcuts that open, read or write, and close the file in one step:
f = d / "note.txt"
n = f.write_text("hello\nworld\n", encoding="utf-8")
print(n, f.exists(), f.is_file())
print(repr(f.read_text(encoding="utf-8")))
print(f.read_text(encoding="utf-8").splitlines())
12 True True
'hello\nworld\n'
['hello', 'world']
write_textreturns the number of characters written (and overwrites, like mode"w").read_textreturns the whole content; always giveencoding="utf-8".read_bytesandwrite_bytesdo the same for binary data (lesson 15.8).f.open("w", encoding="utf-8")returns a file object for line-by-line work, likeopen(f, ...):
with f.open("w", encoding="utf-8") as h:
h.write("via open\n")
print(f.read_text(encoding="utf-8").strip())
via open
f.stat().st_size gives the file size in bytes (and other facts such as the time of modification).
6. Absolute paths and the current folder
print(Path.cwd()) # the current working folder
print(Path.home()) # the user's home folder
print(Path("x").resolve()) # the absolute version of a relative path
These print machine-specific folders, so their output is not shown here. Path("a/../b").resolve() also removes .. pieces, which means "go up one folder".
A very common source of FileNotFoundError is a relative path that is relative to the wrong folder: the program is started from somewhere else than you expected. When a file sits next to your script, build its path from the script's own location:
here = Path(__file__).parent
data_file = here / "data.txt"
__file__ is the path of the running script, so this works whatever folder the program is started from. (It exists in scripts, not in an interactive session.)
7. Renaming and deleting
g = d / "other.txt"
f.rename(g)
print(f.exists(), g.exists())
g.replace(d / "final.txt")
print(sorted(x.name for x in d.iterdir()))
False True
['final.txt']
rename(target)moves or renames;replace(target)does the same but overwrites an existing target without complaint. Both return the new path.d.iterdir()yields what is inside a folder (lesson 15.5 covers folders fully).
Deleting is permanent (no recycle bin):
(d / "final.txt").unlink()
print(list(d.iterdir()))
(d / "final.txt").unlink(missing_ok=True) # no error if already gone
d.rmdir() # only if the folder is empty
print(d.exists())
[]
False
unlink()deletes a file; it raisesFileNotFoundErrorif it is missing, unless you passmissing_ok=True.rmdir()removes an empty folder. For a folder with contents, useshutil.rmtree(folder), which is irreversible; be careful.
8. pathlib versus os.path
Older programs use strings and os.path:
| Task | os.path (older) |
pathlib |
|---|---|---|
| join | os.path.join("a", "b") |
Path("a") / "b" |
| file name | os.path.basename(p) |
p.name |
| folder | os.path.dirname(p) |
p.parent |
| exists | os.path.exists(p) |
p.exists() |
| read all | open(p).read() |
p.read_text() |
Both work. For new code, pathlib is clearer and shorter. Convert with str(p) and Path(s) when a library needs a string.
Worked example: saving reports by year
save_report creates the folder site/reports/<year>/ if needed and writes <name>.txt inside it. backup writes a copy next to a file, named <stem>_backup<suffix>. All paths are built with Path, so the code runs on any system.
from pathlib import Path
import shutil
def save_report(root, year, name, text):
folder = Path(root) / "reports" / str(year)
folder.mkdir(parents=True, exist_ok=True)
path = folder / f"{name}.txt"
path.write_text(text, encoding="utf-8")
return path
def backup(path):
path = Path(path)
target = path.with_name(path.stem + "_backup" + path.suffix)
target.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
return target
p1 = save_report("site", 2025, "sales", "total: 120\n")
p2 = save_report("site", 2026, "sales", "total: 150\n")
b = backup(p2)
for p in (p1, p2, b):
print(p.as_posix(), "|", p.parent.name, p.stem, p.suffix)
print(p2.read_text(encoding="utf-8").strip())
shutil.rmtree("site")
print(Path("site").exists())
site/reports/2025/sales.txt | 2025 sales .txt
site/reports/2026/sales.txt | 2026 sales .txt
site/reports/2026/sales_backup.txt | 2026 sales_backup .txt
total: 150
False
| Step | Idea |
|---|---|
Path(root) / "reports" / str(year) |
joins parts; the year is converted to text first |
mkdir(parents=True, exist_ok=True) |
creates every missing folder, and is safe to repeat |
with_name(stem + "_backup" + suffix) |
builds the backup name from the parts |
read_text / write_text |
short code for small files |
shutil.rmtree |
removes the whole demo folder at the end (use with great care) |
The figures are made up.
Common mistakes
- Joining paths with
+and hard-coded separators. - Assuming a relative path starts where the script is, when it starts at the current working folder.
- Forgetting
parents=Truewhen creating nested folders, orexist_ok=Truefor repeat runs. - Thinking
Path("x")creates the file. - Using
write_texton an existing file by accident (it overwrites). - Using
strmethods on aPath(usep.name, notp.split("/")), or forgetting to convert tostrfor a library that needs it. - Deleting with
rmtreeorunlinkon a wrong path.
Key takeaways
- Use
pathlib.Pathfor paths; join with/, never with manual separators. - Read parts with
name,stem,suffix,parent; build variants withwith_suffix,with_name,with_stem. exists,is_file,is_dircheck the disk;mkdir(parents=True, exist_ok=True)creates folders.read_text/write_texthandle small files in one call;open()gives a file object.- Relative paths depend on the current folder; use
Path(__file__).parentfor files next to the script. rename,replace,unlinkandrmdirchange the disk; deletion is permanent.
Practice
1. What are name, stem and suffix of Path("notes/todo.txt")?
Show answer
todo.txt, todo and .txt.
2. Build the path reports/2026/jan.csv from separate pieces.
Show answer
Path("reports") / "2026" / "jan.csv"
3. What does Path("out").mkdir(parents=True, exist_ok=True) allow?
Show answer
It creates missing parent folders, and does not fail if the folder already exists.
4. How do you open data.txt located in the same folder as the script, whatever folder the program is started from?
Show answer
Path(__file__).parent / "data.txt"
5. What is the difference between unlink() and rmdir()?
Show answer
unlink() deletes a file; rmdir() deletes an empty folder.
6. Does creating Path("new.txt") create a file?
Show answer
No, a Path is just a name. A file appears only when you write to it (for example with write_text or open(..., "w")).