The open
builtin can open files in different modes, which are provided as a combination of characters. Using an invalid sequence of
characters will at best make open
fail, or worse, it will have an undefined behavior (ex: it might ignore some characters).
A valid mode:
- should contain one and only one of the following characters: "r" (read), "w" (write), "a" (append), "x" (create).
- should contain zero or one of the following characters: "t" (text), "b" (binary).
- should contain zero or one "+" character (open for updating)
- cannot contain "a", "w", "+", or "x" if "U" (universal newlines) is used. Note that "U" has no effect in python 3, it is deprecated and
shouldn’t be used anymore.
This rule raises an issue when an invalid "mode" is provided to the open
builtin.
Noncompliant Code Example
# In python 3 the following fails
# In python 2.7.16 on MacOs, "open" will just ignore the "w" flag
with open("test.txt", "aw") as f: # Noncompliant
pass
Compliant Solution
with open("test.txt", "a") as f:
pass
See