Module 13 · File Handling — topic 14 of 15
pathlib
The modern, object-oriented way to work with files and folders: Path objects, joining with /, name, stem, suffix and parent, read_text and write_text, mkdir, iterdir, glob and rglob, and stat.
Learning objectives
- Create and combine Path objects
- Read and write files with Path methods
- Search folders with glob and rglob
Definition
pathlib provides Path objects that represent file-system paths. Paths are joined with the / operator and offer methods for reading, writing, listing, searching and inspecting files.
Introduction
pathlib replaces a dozen os.path functions with one consistent object. Code becomes shorter and reads almost like English.
Why it matters
Most modern Python code and libraries accept and return Path objects. Using pathlib makes file code cleaner and portable by default.
Detailed explanation
Create a path with Path("data") and extend it with /: Path("data") / "raw" / "file.csv".
Properties: name (file name), stem (name without suffix), suffix (extension), parent (containing folder), parts (all components).
Path.cwd() and Path.home() give the working directory and home folder; path.resolve() makes a path absolute.
Quick file I/O: write_text(text, encoding=...) and read_text(encoding=...), plus write_bytes and read_bytes. For larger or incremental work use path.open() like open().
path.exists(), is_file() and is_dir() check the disk; path.mkdir(parents=True, exist_ok=True) creates folders; unlink() deletes a file.
iterdir() lists a folder; glob("*.py") matches in one folder; rglob("*.py") searches recursively.
path.stat().st_size gives the size in bytes; relative_to() and as_posix() help display paths consistently.
with_suffix(".txt") and with_name("other.csv") return new paths with a changed extension or file name, which is handy for creating output files next to their inputs. Path objects are immutable, so these methods never change the original path.
Syntax
- / joins paths.
- read_text/write_text for quick I/O.
- glob/rglob search.
Code examples
Path basics
pathlib makes files easy today.txt today .txt True
Finding files with glob
['a.py', 'b.py'] ['.py', '.py', '.txt']
More examples
Summarising a project folder
{'css/style.css': 14, 'index.html': 13, 'js/app.js': 14, 'js/util.js': 8}
total bytes: 49
{'.css': 1, '.html': 1, '.js': 2}Step-by-step explanation
- mkdir(parents=True) creates css and js folders as needed.
- rglob("*") visits every file and folder; is_file filters to files.
- relative_to and as_posix give the same display on every operating system.
Expected output
Running “Summarising a project folder” prints exactly:
Practical applications
- Static-site generators collecting source files.
- Scripts that find and process all images in a folder tree.
Best practices
- Prefer pathlib for new code.
- Pass encoding to read_text/write_text.
- Use as_posix() when displaying paths consistently.
Common mistakes
Joining Paths with +
Avoid
Prefer
Path objects don't support +; use /.
Using read_text on huge files
Avoid
Prefer
read_text loads the entire file into memory.
Important notes
- Path objects can be passed directly to open(), json, csv and most libraries.
Key takeaways
- Path objects represent paths; / joins them.
- read_text/write_text for simple I/O.
- glob/rglob find files.
Try it yourself
- 1List the five largest files in a folder tree using rglob and stat.
- 2Rename every .jpeg file in a folder to .jpg using Path.with_suffix and rename.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?