After this lesson you will be able to build file and folder paths safely, ask questions about them, create folders and find files, without worrying about whether you are on Windows, macOS or Linux. The tool for this is pathlib, part of Python's standard library.
From strings to Path objects
You could write paths as plain strings such as "reports/2026/sales.csv", but then separators differ between systems and every task needs string slicing. pathlib.Path represents a path as an object with useful behaviour.
from pathlib import Path
folder = Path("reports")
file = folder / "2026" / "sales.csv"
print(file)
print(isinstance(file, Path))reports/2026/sales.csv
TrueThe / operator joins parts. The result is printed with the separator your system uses. On Windows you would see backslashes instead of the forward slashes shown here, and the same code runs unchanged.
The parts of a path
A path knows its own pieces, so there is no need for string slicing.
p = Path("reports/2026/sales.csv")
print(p.name)
print(p.stem)
print(p.suffix)
print(p.parent)
print(p.parts)
print(p.with_suffix(".json"))
print(p.with_name("totals.csv"))sales.csv
sales
.csv
reports/2026
('reports', '2026', 'sales.csv')
reports/2026/sales.json
reports/2026/totals.csvname is the last piece, stem is the name without its extension, and suffix is the extension including the dot. The with_suffix and with_name methods return new paths and change nothing on disk. Paths are never modified in place.
Checking what exists
Making a path object does not touch the disk. Ask questions when you need to know.
p = Path("reports/2026/sales.csv")
print(p.exists())
print(Path(".").is_dir())False
TrueCreating folders
mkdir creates a folder. parents=True also creates any missing folders above it, and exist_ok=True stops it complaining if the folder is already there. Together they make a safe "make sure this folder exists" call.
p.parent.mkdir(parents=True, exist_ok=True)
print(p.parent.is_dir())TrueReading and writing small files
For small text files, write_text and read_text do the opening, the closing and the work in a single call.
p.write_text("region,total\nNorth,120\nSouth,95\n", encoding="utf-8")
print(p.exists())
print(p.is_file())
print(p.read_text(encoding="utf-8"))True
True
region,total
North,120
South,95These methods are perfect for small files. For large files, or when you want to loop over lines, use p.open() inside a with block, which works just like the built-in open().
with p.open(encoding="utf-8") as f:
for line in f:
print(line.strip().upper())REGION,TOTAL
NORTH,120
SOUTH,95Listing and searching folders
iterdir() gives everything directly inside a folder, in no guaranteed order, so sort when the order matters. glob() finds paths matching a pattern, where * means any text, and rglob() searches all the subfolders as well.
(Path("reports") / "2026" / "notes.txt").write_text("remember to check totals\n", encoding="utf-8")
(Path("reports") / "summary.txt").write_text("year summary\n", encoding="utf-8")
for item in sorted(Path("reports").iterdir()):
print(item, "folder" if item.is_dir() else "file")
print([str(x) for x in sorted(Path("reports").glob("*.txt"))])
print([str(x) for x in sorted(Path("reports").rglob("*.txt"))])reports/2026 folder
reports/summary.txt file
['reports/summary.txt']
['reports/2026/notes.txt', 'reports/summary.txt']The first glob only looked inside reports, so it found one file. The rglob looked inside reports/2026 as well, so it found two.
Renaming and deleting
rename moves or renames a path and unlink deletes a file. Be careful, because deleted files do not go to a recycle bin.
summary = Path("reports") / "summary.txt"
renamed = summary.rename(Path("reports") / "year-summary.txt")
print(renamed)
print(summary.exists())
renamed.unlink()
print(renamed.exists())reports/year-summary.txt
False
FalseBuilding paths that do not depend on the folder you run from
A relative path depends on where the program was started, which was the problem raised in the reading-files lesson. In a saved script, a reliable trick is to anchor paths to the script's own location. The special name __file__ holds the script's path, but it exists only when running a script file, so this example is not run here.
from pathlib import Path
BASE = Path(__file__).resolve().parent
data_file = BASE / "data" / "loans.csv"Path.home() gives the current user's home folder and Path.cwd() the current working directory. Both are useful, but their results differ for every computer.
Common mistakes
- Joining with
+.Path("a") + "b"raises aTypeError. Use the/operator. - Expecting
iterdir()to be sorted. Wrap it insorted()when the order matters. - Calling
mkdir()twice. The second call fails withFileExistsErrorunless you passexist_ok=True. - Hard-coding backslashes.
"data\\file.txt"works only on Windows. UsePath("data") / "file.txt". - Forgetting that a
Pathis not a string. Many functions accept paths, but if one wants a string, wrap the path instr().
Exercise
Create a folder library/books, write a file dune.txt inside it with the text Frank Herbert, then print the file's name, its suffix and its contents. Finally, print a sorted list of every .txt file under library.
Show one possible answer
from pathlib import Path
books = Path("library") / "books"
books.mkdir(parents=True, exist_ok=True)
book = books / "dune.txt"
book.write_text("Frank Herbert", encoding="utf-8")
print(book.name)
print(book.suffix)
print(book.read_text(encoding="utf-8"))
print([str(x) for x in sorted(Path("library").rglob("*.txt"))])dune.txt
.txt
Frank Herbert
['library/books/dune.txt']Next comes the modules section, starting with how to import code from other files. A video version of this topic is in the video course at /learn/python/.
Key points
- pathlib.Path treats a path as an object, and the / operator joins parts so you do not glue strings together.
- A path has parts you can read: name, stem, suffix, parent and parts.
- exists(), is_file() and is_dir() check what is there, and mkdir(parents=True, exist_ok=True) creates folders safely.
- read_text() and write_text() handle small files in one call, and iterdir() and glob() list and search folders.
- The same code works on Windows, macOS and Linux, because Path uses the right separator for each.