pathlib gives Python an object-oriented way to work with file and folder paths.
A Path object is easier to combine, inspect, and pass around than raw string paths.
Use pathlib when code needs to read files, write reports, scan folders, or build paths that work across operating systems.
Path objects can represent files or folders without immediately opening them.
from pathlib import Path
base = Path("reports")
file_path = base / "january.txt"
print(file_path)
reports\january.txt
Path joins the folder and file name using the correct path style for the system.
Path has convenient read_text() and write_text() helpers for small text files.
from pathlib import Path
path = Path("note.txt")
path.write_text("Learn pathlib", encoding="utf-8")
print(path.read_text(encoding="utf-8"))
Learn pathlib
write_text() creates or replaces the file, and read_text() reads it back as a string.
glob() finds files that match a pattern inside a folder.
Path bugs usually come from assuming the current working directory.
0 of 2 checked
Try this next
0 of 3 completed
pathlib is usually clearer for new code because paths become objects with useful methods. os.path is still common in older code.
No. A Path object can point to a location that does not exist yet. Writing or mkdir() creates something.
Avoid it for very large files. Use open() and process the file line by line instead.
Explore 500+ free tutorials across 20+ languages and frameworks.