> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Ensure File Closed

#### Sourcery refactoring id: `ensure-file-closed`

#### Description:

Use `with` when opening file to ensure closure

#### Before:

```python
file = open("welcome.txt")
data = file.read()
print(data)
file.close()
```

#### After:

```python
with open("welcome.txt") as file:
    data = file.read()
    print(data)
```

#### Explanation:

Opening files in this way is more concise, and also ensures that the call to
`file.close()` is not skipped if there is an exception.

It makes use of Python's `with` context manager - under the hood the changed
code behaves like this:

```python
file = open("welcome.txt")
try:
    data = file.read()
    print(data)
finally:
    file.close()
```

The file is closed for you as soon as the block is exited, even where an
exception has been thrown.
