Skip to content
Forge Learn/Modules & Files

Reading/Writing Files & Context Managers

5 min read

You'll learn to

  • -Open a file for reading or writing with `open()` and the correct mode
  • -Explain why `with open(...) as f:` is the correct pattern instead of manual open/close
  • -Read a file's contents line by line or all at once

Every program you have written so far has lived and died in memory - close the program, and everything is gone. Reading and writing files is how a program persists data across runs. This chapter also introduces context managers, a pattern you will recognize again the moment you meet database connections or network sockets later.

open() and File Modes

`open(path, mode)` returns a file object. The mode controls what you can do with it: `"r"` for reading (the default), `"w"` for writing (creates the file if missing, and **overwrites** it if it already exists), and `"a"` for appending to the end of an existing file.

Writing, then reading, a file - the manual (not recommended) way

Why with open(...) as f: Is the Correct Pattern

Manually calling `.close()` has a real problem: if an exception is raised between `open()` and `.close()`, the `.close()` call never runs, and the file is left open - which can mean data never gets flushed to disk, or the file stays locked for other programs. A `with` block is Python's "context manager" syntax: it guarantees `.close()` runs automatically when the block exits, whether it exits normally or via an exception.

The correct pattern: with open(...) as f:

Always prefer `with open(...) as f:` over manual `open()`/`.close()` pairs. It is shorter, and it is correct in the presence of exceptions in a way that manual closing is not.

Reading Line by Line

A file object is itself iterable line by line, which is memory-efficient for large files - you never have to load the whole file into memory at once the way `.read()` does.

Iterating over a file line by line
  • -`"r"`: read (file must already exist). `"w"`: write, overwriting any existing content. `"a"`: append to the end.
  • -`with open(...) as f:` guarantees the file is closed even if an exception occurs inside the block - always prefer it.
  • -`f.read()` loads the whole file as one string; iterating over `f` (or `f.readlines()`) gives you it line by line.
ScaleDojo Logo
Initializing ScaleDojo