# The with statement in Python

> Learn how the with statement in Python simplifies exception handling, automatically closing a file you open with open() so you do not have to call close().

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-01-29 | Topics: [Python](https://flaviocopes.com/tags/python/) | Canonical: https://flaviocopes.com/python-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:

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

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

You can write:

```python
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.
