with statement

A statement that sets something up, runs a block, and guarantees the matching clean-up afterwards, most often closing a file.

In more detail

with open(name) as f: closes f when the block ends, even if an exception is raised inside it, so you can never forget the close. The object after with is a context manager.

Example

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

Related terms

Taught in

References

Certification courses