Skip to content

open-file-without-with

Pythonsuspiciousno fixdefault: offpython/ruff

Reports a call of open or tempfile.NamedTemporaryFile and the like that is not the context of a with, is not returned and is not given to enter_context.

A file that is not closed explicitly is closed when the object is freed, which depends on the interpreter and on references that remain, and on an error between the open and the close it stays open. Handles that stay open run a process out of descriptors, and buffered data may not be written.

To fix, open the file in a with statement.

Reported
...
x = 1
f = open("a")
...
python:
lint:
rules:
open-file-without-with: warn # off (default), warn, error

Enabled by the presets: python/ruff.

Suppress one line with sudsy-disable-next-line open-file-without-with in a comment of the file’s language.

The same check in other tools; Sudsy reports what each upstream rule reports.

Tool Rule Match
ruff SIM115 full