Skip to content

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.

Beginner 10 min read·Lesson 207 of 306 in Python Programming

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

Python
from pathlib import Path
report = Path("reports") / "2026" / "summary.txt"
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text("done\n", encoding="utf-8")
print(report.read_text(encoding="utf-8"))
for py in Path(".").rglob("*.py"):
print(py)
  • / joins paths.
  • read_text/write_text for quick I/O.
  • glob/rglob search.

Code examples

Path basics

Python
from pathlib import Path
p = Path("notes") / "today.txt"
p.parent.mkdir(exist_ok=True)
p.write_text("pathlib makes files easy\n", encoding="utf-8")
print(p.read_text(encoding="utf-8").strip())
print(p.name, p.stem, p.suffix, p.exists())
Output
pathlib makes files easy
today.txt today .txt True

Finding files with glob

Python
from pathlib import Path
for name in ["a.py", "b.py", "c.txt"]:
Path(name).write_text("x", encoding="utf-8")
print(sorted(p.name for p in Path(".").glob("*.py")))
print(sorted(p.suffix for p in Path(".").iterdir()))
Output
['a.py', 'b.py']
['.py', '.py', '.txt']

More examples

Summarising a project folder

Python
from pathlib import Path
root = Path("site")
files = {"index.html": "<h1>Home</h1>", "css/style.css": "body{margin:0}",
"js/app.js": "console.log(1)", "js/util.js": "export{}"}
for rel, content in files.items():
path = root / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
sizes = {}
for path in sorted(root.rglob("*")):
if path.is_file():
sizes[path.relative_to(root).as_posix()] = path.stat().st_size
print(sizes)
print("total bytes:", sum(sizes.values()))
by_ext = {}
for path in root.rglob("*.*"):
by_ext[path.suffix] = by_ext.get(path.suffix, 0) + 1
print(dict(sorted(by_ext.items())))
Output
{'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:

TextOutput
{'css/style.css': 14, 'index.html': 13, 'js/app.js': 14, 'js/util.js': 8}
total bytes: 49
{'.css': 1, '.html': 1, '.js': 2}

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

Path("data") + "/file.txt"

Prefer

Path("data") / "file.txt"

Path objects don't support +; use /.

Using read_text on huge files

Avoid

for line in big.read_text().splitlines(): ...

Prefer

with big.open(encoding="utf-8") as f:
for line in f: ...

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

  1. 1
    List the five largest files in a folder tree using rglob and stat.
  2. 2
    Rename 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?
Practise this topic