---
title: Use Context Manager for File and Resource Handling
impact: MEDIUM
impactDescription: Not using with statement for file/network/lock resources causes resource leaks when exceptions are raised, leading to open file handles, locked databases, and memory exhaustion.
tags: python, resources, context-manager, files, quality
---

## Use Context Manager for File and Resource Handling

Python's `with` statement (context manager protocol) guarantees that resources are released even when exceptions occur. Always use `with` when dealing with files, network connections, database cursors, threading locks, and any object that implements `__enter__`/`__exit__`.

**Incorrect:**
```python
# File handle not closed if exception occurs
f = open("data.txt", encoding="utf-8")
content = f.read()  # If this raises, f.close() is never called
f.close()

# Lock never released if exception raised inside
lock = threading.Lock()
lock.acquire()
do_work()  # Exception here leaves lock permanently acquired
lock.release()
```

**Correct:**
```python
# File is always closed, even on exception
with open("data.txt", encoding="utf-8") as f:
    content = f.read()

# Lock always released
import threading

lock = threading.Lock()
with lock:
    do_work()

# Multiple context managers in one with
with open("input.txt", encoding="utf-8") as fin, \
     open("output.txt", "w", encoding="utf-8") as fout:
    fout.write(fin.read())
```

**contextlib.suppress as context manager:**
```python
import contextlib

# Instead of try/except/pass
with contextlib.suppress(FileNotFoundError):
    os.remove("temp.txt")
```

**Tools:** Ruff `SIM115` (open-file-with-context-handler), `R1732` (consider-using-with), Pylint, flake8-simplify
