Python, `with` statement

ThiswithThe statement is very helpful for simplifying exception handling.

For example, when working with a file, you must remember to close it every time you open a file.

withMake this process transparent.

Instead of writing:

filename = '/Users/flavio/test.txt'

try: file = open(filename, ‘r’) content = file.read() print(content) finally: file.close()

You can write:

filename = '/Users/flavio/test.txt'

with open(filename, ‘r’) as file: content = file.read() print(content)

In other words, we have built-in implicit exception handling, such asclose()Will be called automatically for us.

withNot only helps to process files. The above example is only used to introduce its function.


More python tutorials: