Context managers power Python's with blocks. They sandwich a code block between enter code and exit code. They're most often used for reusing common cleanup/teardown functionality.

Files opened with with close automatically

Context managers are objects that can be used in Python's with statements.

You'll often see with statements used when working with files in Python.

This code opens a file, uses the f variable to point to the file object, reads from the file, and then closes the file:

>>> with open("my\_file.txt") as f:... contents = f.read()...

Notice that we didn't explicitly tell Python to close our file.

But the file did close:

>>> f.closedTrue

The file closed automatically when the with block was exited.

Context managers work in with statements

Any object that can be …

Read the full article: https://www.pythonmorsels.com/what-is-a-context-manager/