Invalid open() Mode
ID |
python.invalid_open_mode |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Python |
Tags |
reliability, suspicious-call |
Description
Reports open(path, mode) calls whose mode string is not a valid file-mode specifier. Python’s open() accepts a tightly constrained mode string:
-
exactly one of
r,w,a,x(read, write, append, exclusive create), -
at most one of
b,t(binary or text — text is the default), -
at most one
+(read-and-write upgrade).
Anything else raises ValueError at runtime — a latent defect that only surfaces when the path is exercised.
open(p, "rw") # FLAW — r and w both present
open(p, "rb+w") # FLAW — r and w combined
open(p, "z") # FLAW — unknown mode character
open(p, "") # FLAW — empty mode
open(p, "r") # OK
open(p, "rb+") # OK
open(p, "wt") # OK
Rationale
Mode-string typos slip past static type checking because the parameter is just str. The error appears the first time the function actually runs against a real path, often in production. Catching it statically removes the latent failure.
Remediation
Use a single read/write/append/exclusive-create mode character, optionally followed by b or t, optionally followed by +. Common forms:
open(p, "r") # text read (the default — same as open(p))
open(p, "rb") # binary read
open(p, "w") # text write — truncates
open(p, "a") # text append
open(p, "x") # exclusive create — fails if path exists
open(p, "rb+") # binary read + write
open(p, "wt") # text write (explicit)