Part 08 / Topic 6 of 10
pathlib: working with paths
A path is the address of a file, like bills/2025/electricity_jan.txt. pathlib.Path is the modern way to handle paths. It works the same on Windows, macOS and Linux. Join parts with /.
Real-world example: organise monthly bill files.
from pathlib import Path
folder = Path("demo_bills") / "2025"
folder.mkdir(parents=True, exist_ok=True) # make folders, no error if present
bill = folder / "electricity_jan.txt"
bill.write_text("₹1,240", encoding="utf-8") # open + write + close in one line
print(bill.exists()) # True
print(bill.read_text(encoding="utf-8")) # ₹1,240
print(bill.name) # electricity_jan.txt
print(bill.stem, bill.suffix) # electricity_jan .txt
print(bill.parent) # demo_bills/2025 (Windows: demo_bills\2025)
print([p.name for p in folder.glob("*.txt")]) # ['electricity_jan.txt']
bill.unlink() # delete the file
folder.rmdir() # delete the empty 2025 folder
folder.parent.rmdir() # delete the empty demo_bills folder
print(folder.parent.exists()) # False
| Task | pathlib |
|---|---|
| Join paths | Path("data") / "marks.csv" |
| Does it exist? | p.exists(), p.is_file(), p.is_dir() |
| Read / write small text | p.read_text(encoding="utf-8"), p.write_text(text, encoding="utf-8") |
| Make folders | p.mkdir(parents=True, exist_ok=True) |
| Make an empty file | p.touch() (if it exists, only its "modified" time changes) |
| Rename / move | p.rename(new_path): returns the new Path; new_path can be in another folder. ⚠️ If new_path already exists, Windows raises FileExistsError but macOS / Linux silently replace it, so check new_path.exists() first |
| Find files | p.glob("*.csv"), p.rglob("*.csv") (all sub-folders) |
| Parts | p.name, p.stem, p.suffix, p.parent |
| Delete | p.unlink() (file), p.rmdir() (empty folder) |
| Folder of this script | Path(__file__).parent |
Tip:
open("data.txt")looks in the current working folder, which depends on where you run Python from. To always find files next to your script, usePath(__file__).parent / "data.txt". All the examples in this part do this.
🔍 Going deeper: a
Pathworks anywhere a path string is accepted (open(),csv,json,os). Useful extras:Path.cwd(),Path.home(),p.resolve()(full absolute path),p.with_suffix(".bak").globgives results in no fixed order, so wrap it insorted()when order matters.
Read more: the official pathlib documentation.
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.