0% complete

Files, data formats, and web APIs · Lesson 1 of 3

Paths and files with pathlib

Work with filesystem paths and context-managed file operations.

Lesson

1. Concept and mental model

pathlib.Path represents a filesystem path using an interface that works across operating systems. Build child paths with / rather than manually joining strings with a platform-specific separator. Use methods such as exists(), is_file(), and mkdir() when they clarify the operation, but remember that the filesystem can change between a check and the later read. Handle the actual operation’s exception rather than assuming a prior check guarantees success.

2. How it works

Open files with a context manager: with path.open(...) as file: closes the handle even if processing raises an exception. Specify text encoding, commonly UTF-8, when reading and writing text so behavior does not depend on a machine’s locale. Choose newline appropriately for CSV files. Use binary mode for bytes and text mode for decoded characters; confusing these modes can corrupt data.

3. Use it safely and effectively

Avoid overwriting important files without an explicit policy. For automation, validate the target directory, use a dry-run option when operations are destructive, and report which paths will change. Large files should often be processed line by line instead of loading the entire file into memory. Practice by reading a log file and counting nonempty lines while handling a missing file with an actionable error.

4. Syntax reference

from pathlib import Path

path = Path('notes.txt')
path.write_text('first line\nsecond line\n', encoding='utf-8')
text = path.read_text(encoding='utf-8')
print(len(text.splitlines()))

5. Guided walkthrough

Build a path from a known project or data directory, inspect whether it exists, and use the appropriate text or byte operation. For large files, stream line by line rather than loading the entire file into memory.

6. Common mistakes to avoid

  • Assuming a relative path is resolved from the source file rather than the process working directory.
  • Reading an unbounded file completely when the task can process it as a stream.

Visual guide

Safe file workflow

  1. Step 01 Resolve

    Build the target with pathlib.

  2. Step 02 Open

    Use a context manager and explicit encoding.

  3. Step 03 Process

    Read, validate, and write with a clear policy.

Code examples

Worked example
PYTHON
from pathlib import Path

path = Path('notes.txt')
path.write_text('first line\nsecond line\n', encoding='utf-8')
text = path.read_text(encoding='utf-8')
print(len(text.splitlines()))
Expected output
2
Build a path independently of separators
PYTHON
from pathlib import Path

report = Path('data') / 'reports' / 'summary.txt'
print(report.suffix)
Expected output
.txt
Read a text file with an explicit encoding
PYTHON
from pathlib import Path

path = Path('notes.txt')
if path.exists():
    text = path.read_text(encoding='utf-8')
    print(len(text.splitlines()))
Expected output
Prints the number of lines when notes.txt exists.

Key points

  • Work with filesystem paths and context-managed file operations.
  • Prefer explicit, testable behavior over hidden side effects.
  • Validate assumptions at system boundaries and handle failure deliberately.

Check your understanding

Practice

What does a with block provide for an opened file?

Your learning progress

Finish this lesson