Codectionary / Developer documentation / Python

Python Context Managers

A context manager manages setup and cleanup around a block of code. The with statement calls its cleanup logic even when an exception interrupts the block.

Syntax

with open("notes.txt", encoding="utf-8") as file:
    text = file.read()

Examples

Reading a file safely

A small, runnable example of this syntax.

with open("notes.txt", encoding="utf-8") as file:
    for line in file:
        print(line.rstrip())
# The file is closed after the block.

Best practices

  • Use with for files, locks, and other resources that must be cleaned up reliably.
  • Keep examples small while learning, then combine the idea with a real project.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading