Working with Files: The with statement

The with statement is very helpful to simplify working with exception handling.

For example when working with files, each time we open a file, we must remember to close it.

with makes 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, as close() will be called automatically for us.

with is not just helpful to work with files. The above example is just meant to introduce its capabilities.

Lessons in this unit:

0: Introduction
1: Check if file or directory exists
2: Create an empty file
3: Create a directory
4: Read the content of a file
5: Write to a file
6: List files in a directory
7: Get the details of a file
8: ▶︎ The with statement

Join my AI Workshop!

The Web Development BOOTCAMP cohort starts in February 2026