Lesson · File I/O & Filesystem
pathlib
55 min readpathlib
`pathlib` represents filesystem paths as objects and provides readable cross-platform operations. It usually produces clearer code than manual string concatenation or scattered `os.path` calls.
Learning goals
- Build paths by joining with
/and say what stays a string versus what becomes aPath. - Read a path's parts (
name,stem,suffix,parent) and predict each one from a given path literal. - Check existence and type with
exists(),is_file(), andis_dir()without assuming they agree. - Use
read_textandwrite_textfor small files and say when an explicitopenis still needed. - Traverse a directory with
iterdir()andglob()and state what each returns.
Mental model
A Path is a value object: it stores a path and offers properties and methods without touching the disk until you ask it to. Building one does not check anything, / produces a new Path rather than mutating, and the parts (name, stem, suffix, parent) are pure string surgery. Only calls such as exists(), read_text(), or glob() cross into the filesystem, so path arithmetic can be reasoned about, and tested, separately from I/O.
Core idea
pathlib replaces string concatenation and scattered os.path calls with one object whose operators and properties describe a path, while its methods describe actions on the filesystem. Keep that boundary sharp: constructing and inspecting a Path is pure and platform aware, and only the method calls can fail. Code that respects the line is easier to test, because the arithmetic can be checked without touching disk.
Path objects
Path objects represent filesystem paths and overload / for joining components. They carry operations for inspection, traversal, reading, writing, and manipulation.
Joining paths
The / operator joins a path with a string or another path and returns a new Path; it inserts the separator the platform uses, so Path('a') / 'b' describes the same structure on Windows and POSIX. An absolute right-hand operand replaces everything before it (on POSIX, Path('a') / '/x' is /x), and parent, with_name, and with_suffix all return new paths the same non-mutating way.
Parent/name/stem/suffix
These properties expose the parts of the final component: name is the last segment (summary.txt), stem drops the last suffix (summary), suffix keeps it including the dot (.txt), and parent is everything above it. They are pure string surgery with no disk access, and suffixes plus a second stem application covers names with several dots.
Existence checks
exists(), is_file(), and is_dir() answer questions about the disk at the moment of the call, so the answer can change before the code acts on it. exists() cannot distinguish a file from a directory (use the specific predicates), and a broken symbolic link reports False for exists() while is_symlink() stays True.
Reading/writing
read_text, write_text, read_bytes, and write_bytes open, transfer, and close a file in one call, and write_text truncates an existing file. They are the concise choice for small content; use open when you need line-by-line iteration, an unusual mode such as appending, or a handle kept open across several operations.
Traversal
iterdir() yields the direct children of a directory as Path objects and does not recurse, while glob(pattern) matches names (*.txt) and rglob matches recursively. Both are lazy generators, so wrapping one in list() is a deliberate choice to materialize results, and the matches reflect the directory at iteration time.
Cross-platform paths
Use path abstractions rather than hard-coded separators. pathlib chooses platform-appropriate concrete path behavior while preserving a common API.
Walkthrough
Path("reports")and the/chain build one relative path; no directory is created and no existence check happens, so nothing fails here even thoughreportsmay not exist yet.report.name,report.stem, andreport.suffixdescribe only the last component (summary.txt,summary,.txt), andreport.parentwalks one level up toreports/2026.report.as_posix()renders the same path with forward slashes on any platform, which is what you want when a path must be stored, logged, or compared as text.- Predict before running: each printed line on Windows and on a POSIX system, and what changes if
rootwerePath("/tmp/reports").
Experiments to try
- Call
report.with_suffix(".md")and check the result; confirm thatreportitself is unchanged, because these operations return new paths. - Run the example from two different working directories and explain why the printed parts stay identical while the path's meaning changes.
- Join
root / ".." / "2026"and inspectreport.partsandreport.parent; then callresolve()and compare what the..becomes. - Call
report.exists(), then createreports/2026/withmkdir(parents=True), then call it again; record both results.
Common mistakes
- Treating a
Pathlike a string:report + "/x"raisesTypeErrorbecause/is the join operator, and APIs that require a string needstr(path)(or accept any path-like object). - Assuming
Path("a/../b")normalizes itself:..segments and symlinks stay literal untilresolve()is called, so printed output and equality can surprise. - Checking
exists()and then acting as if the answer still holds: the file can appear or disappear in between, so the actual operation still needs its own error handling. - Forgetting
parents=Trueinmkdir: creatingreports/2026raisesFileNotFoundErrorwhenreportsis missing, because plainmkdironly makes the final directory.
Practice: Easy
- Build
Path("data") / "2026" / "report.tar.gz"and printname,stem,suffix,suffixes, andparent; write down each expected value before printing. - Create a directory with
mkdir(exist_ok=True), write a file withwrite_text, then read it back withread_textand confirm both withexists()andis_file(). - Print
Path("a") / "b"andPath("a") / "/b"and explain why the second join produces a different result on POSIX.
Practice: Medium
- Write
describe(path)returning a dict with name, stem, suffix, parent, and whether the path exists; run it on a path that exists and one that does not, and sketch the output for both before running. - Copy the files from a source directory to a target using
iterdir()andshutil.copy2, preserving names; test on a directory that contains a nested folder and decide what the function should do with directories. - Rewrite an
os.path.joinplusos.path.existsfunction aspathliband list what the new version makes harder to get wrong, especially separators andexpanduser.
Practice: Hard
- Build
find(root, pattern)that walks withrglob, returns sorted matches, filters to files only, and decides how to treat permission errors; test it against a directory you populate with mixed content. - Design a path round-trip test: given a list of path strings, assert that
Path(p).as_posix()and re-parsing the POSIX string produce the same parts on your platform; document one case where round-tripping cannot preserve meaning (Windows separators,..segments, or case-insensitive drives). - Compare
resolve()withabsolute()on a path containing..and a symlink; recordpartsbefore and after each call and state which result you would log in an error message about a missing file.
Lesson checklist
- I can build a path with
/and read back every part of it without touching the disk. - I can choose between
read_text/write_textand an explicitopenfor a given task. - I can iterate or glob a directory and explain the difference between direct children and recursive matches.
- I can say why
exists()cannot be trusted as a guarantee for the next operation.
Remember
`pathlib` turns a path into an object: `/` and properties such as `name` and `parent` are pure, platform-aware string operations, while methods such as `exists`, `read_text`, and `glob` are where the filesystem gets involved. Keep that line visible and path code becomes testable: check the arithmetic in memory, and expect the method calls to be able to fail.
Interview angles
What is the main purpose of **Path objects**?+
Path objects represent filesystem paths and overload / for joining components. They carry operations for inspection, traversal, reading, writing, and manipulation.
What should you pay attention to when using **Joining paths**?+
The / operator joins without touching the disk and returns a new Path; it uses the platform separator, and an absolute right-hand operand replaces the whole path on POSIX, so check which side can be absolute when combining user input.
How does **Parent/name/stem/suffix** fit into this lesson?+
These properties are pure string surgery on the last path segment: name is summary.txt, stem is summary, suffix is .txt, and parent is the containing directory. None of them checks whether anything exists.
What does `mkdir()` raise when the parent directory is missing, and how does `parents=True` change that?+
Plain mkdir raises FileNotFoundError because it creates only the final directory; mkdir(parents=True) creates missing intermediate directories, and exist_ok=True additionally suppresses the error when the leaf already exists.