The with statement in python

The with statement in python

The with statement in python is used for resource management and exception handling. You’d most likely find it when working with file streams. For example, the statement ensures that the file stream process does’t block other processes if an exception is raised, but terminates properly.

The code block below shows the try-finally approach to file stream resource management.

#Python

lang
manifest.py
file = open('file-path', 'w')
try:
    file.write('Hello world')
finally:
    file.close()
Copied!

Normally, you’d want to use this method for writing to a file, but the with statement offers a cleaner approach:

lang
manifest.py
with open('file-path', 'w') as file:
    file.write('Hello world')
Copied!

The with statement simplifies our write process to just two lines.