A file is opened and used in one expression, so nothing closes it

tx0/python:file-not-closedrecommendedwarningbug

What it finds

open(path).read(): the file object is never closed by the code, only when the garbage collector gets to it, which on interpreters other than CPython can be much later. Until then the descriptor stays open, writes may not be flushed, and Python warns with ResourceWarning. with open(path) as f: closes it, as do Path.read_text and Path.write_text.

Reported are files opened with the builtin open with a method called on the result right away, so that nothing can close it. A file passed to a call is left alone, since the callee may take it over and close it.

From the rule's source, file_not_closed.rs.

Example from the rule's tests
import jsonfrom contextlib import closing  def load(path):    data = open(path).read()tx0 reports: this file is never closed: a method is called on it at once    config = json.load(open(path))    with open(path) as handle:        text = handle.read()    with closing(open(path)) as other:        rest = other.read()    return data, config, text, rest
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/python:file-not-closed" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:file-not-closed] reason="..."

tx0 explain tx0/python:file-not-closed shows the same in the terminal. Found a false positive? Report it.