Python has a a with
statement that simplifies exception handling. Suppose that we are dealing with files in our Python program. Without using with
we would write a program in the following manner:
filename='file.txt'
try:
file: = open(filename, 'r')
contentOfFile = file.read()
print(contentOfFile)
finally:
file.close()
Using the with
statement:
filename='file.txt'
with open(filename, 'r')
contentOfFile = file.read()
print(contentOfFile)
By using the with
statement, the close()
method will automatically be called and the file will be closed. The with
statement is not just exclusive to files, but the above example was just to show some of what it is capable of.