Context Manager
Context Manager
ipynb - Colab
Motivations
Let's use reading and writing from files as an example. Python has a function called open , which
assigns a file object to a variable, so that you can perform some task such as reading from or
writing to the file. We call that variable that refers to a file object a "file handle". To write some
data to a file, you must first call open on the filepath:
If a file is updated without closing it, the data will not be stored in the target file. In the code
block below, the string Will i be stored in the file? has not yet been saved to hello.txt .
29
To save it, you must also release the file handle using the . close() method:
file.close()
You can avoid the risk of forgetting to close the file (and thereby failing to save your data) by
using context managers. Python uses the with keyword to denote the start of a context
management code-block. Context managers have the following syntax:
This is telling the Python interpreter that, during the following codeblock (and only that
codeblock), the interpreter should open the hello.txt file object in write ( w ) mode, and assign
it to the variable file . Once the indented block following the with statement is finished, this
will no longer be the case. The file variable will no longer be associated with that context, and
the file object will be closed.
As well as w for write, there are various other update modes for the open function. Here is a full
list of the options:
't' (Text Mode): Used with other modes for interacting text files (e.g., 'rt' , 'wt' ),
usually not needed as it represents default behaviour
'+' (Update Mode): Used with other modes to read and write to the same file