File resources are not reliably released

File resources are not reliably released

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 with cannot be used, ensure that close() runs in a try/finally block.

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 with statement or a guaranteed close() 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.

References