First, what With statement is?
There are some tasks, you may need to set in advance, and afterwards do the cleanup work. For this scenario, Python with statement provides a very convenient approach. A good example is the file handle, you need to obtain a file handle to read data from the file, and then close the file handle.
If not with the statement, as follows:
file =open('1.txt', 'r', encoding="utf-8")
ret = file.read()
print(ret)
file.close()
There are two issues:
One may forget to close the file handle;
the second is the occurrence of abnormal data file read, without any treatment.
This time is a go with the time. In addition to a more elegant syntax, with also a good handle exceptions context of the environment.
with open('1.txt', encoding="utf-8") as file: print(file.read())