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

Use with open(...) as f: and perform the read inside the block. Leaving the block closes the file even if the read fails. If a context manager cannot be used, call close() in the finally clause of try/finally.

Examples

Before

python
handle = open(path)
return handle.read()

After

python
with open(path) as handle:
    return handle.read()

The original example never explicitly closes the file. The revised context manager closes it when return exits the block or read() raises an exception.

References