🎓 A1Learner
🔍

Python With Statement in Depth

A context manager is an object that sets up a block and cleans up after it. Cleanup also runs when an error ends the block early.

A file stays open until close()

This code opens a file and writes to it.

file = open("notes.txt", "w")
file.write("Keep this safe")
print(file.closed)

A file opens and closes itself

This snippet assumes a file named notes.txt. Its text is Keep this safe, with no extra lines.

with open("notes.txt") as f:
    text = f.read()
print(text)
print(f.closed)

The as target

The name after as is the as target. Here it holds the open file itself.

with open("notes.txt") as f:
    print(f.name)

Cleanup runs even when code fails

An error ends the block early. The file still closes before your except runs.

try:
    with open("notes.txt") as f:
        raise ValueError("something went wrong")
except ValueError:
    print("The error was caught.")
print(f.closed)

Two managers in one statement

This snippet assumes two files. The file a.txt holds Apples and b.txt holds Bread.

with open("a.txt") as first, open("b.txt") as second:
    print(first.read())
    print(second.read())

Example

lines_to_save = ["First line", "Second line", "Third line"]
with open("source.txt", "w") as source_out:
    for line in lines_to_save:
        source_out.write(line + "\n")

with open("source.txt") as source, open("copy.txt", "w") as copy:
    for line in source:
        copy.write(line)

with open("copy.txt") as check:
    print(check.read(), end="")

Key points

  • Context manager: an object that sets up a block and cleans up after it
  • Use with to run a block under a context manager
  • The as target: the name after as holds the value the manager hands you
  • Exit code: the cleanup step that runs when the block ends, however it ends
  • Use one with line with commas to run several managers together

In this example, the first with block writes three lines into source.txt. The file closes when that block ends. The second with line opens two managers at once. The name source reads the old file. The name copy writes the new file. The loop copies one line at a time. Both files close when the block ends. The last with block reads copy.txt back. It prints the text to prove the copy worked.

Note

A with block suppresses nothing by default.

An error inside still reaches your code after cleanup runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Code inside a with block raises an error in the middle. What happens to the open file?