Last but not least, the with statement is usually used with any kind of connections or managed resources such as file handles. Consider the following example:
with open('./text_file.txt', 'r') as file:
data = file.read()
print(data)
Here, we use a with clause together with the open() function. The open function returns a file-like object that has __enter__ and __exit__ methods, representing the opening and closing of the file. Both can be used directly, but the file needs to be closed properly once it is opened. The close() function along together with the with clause does exactly that – it opens an object, and makes sure it is closed (using those two methods) at the end. Essentially, it is the equivalent of the following try/finally statement:
try:
file = open('./text_file.txt', 'r').__enter__...