Description
Using a file acquired with open() without a with statement or a guaranteed close() call can leak a file descriptor when an exception occurs.
Potential impact
- Repeated requests may exhaust file descriptors and cause denial of service.
- File locks may persist, or temporary-file cleanup may be delayed.
Remediation
- Open files with
with open(...) as f:. - If
withcannot be used, ensure thatclose()runs in atry/finallyblock.
Examples
Before
python
handle = open(path)
return handle.read()
After
python
with open(path) as handle:
return handle.read()
Explanation:
- Before: The file is opened without a
withstatement or a guaranteedclose()call, so an exception may leave its descriptor open. - After: Opening the file with
with open(...) as f:closes it automatically when the block ends.