python.lang.correctness.writing-to-file-in-read-mode.writing-to-file-in-read-mode

Author
7,892
Download Count*
License
The file object '$FD' was opened in read mode, but is being written to. This will cause a runtime error.
Run Locally
Run in CI
Defintion
rules:
- id: writing-to-file-in-read-mode
message: The file object '$FD' was opened in read mode, but is being written to.
This will cause a runtime error.
patterns:
- pattern-either:
- pattern-inside: |
$FD = open($NAME, "r", ...)
...
- pattern-inside: |
$FD = open($NAME, "rb", ...)
...
- pattern-inside: |
with open($NAME, "r", ...) as $FD:
...
- pattern-inside: |
with open($NAME, "rb", ...) as $FD:
...
- pattern: $FD.write(...)
severity: ERROR
languages:
- python
metadata:
category: correctness
technology:
- python
license: Commons Clause License Condition v1.0[LGPL-2.1-only]
Examples
writing-to-file-in-read-mode.py
fout = open("example.txt", 'w')
print("stuff")
# ok:writing-to-file-in-read-mode
fout.write("I'm writable!")
fout.close()
fout = open("example.txt", 'r')
print("stuff")
# ruleid:writing-to-file-in-read-mode
fout.write("whoops, I'm not writable!")
fout.close()
with open("example.txt", 'rb') as fout:
# ruleid:writing-to-file-in-read-mode
fout.write("whoops, me neither!")
Short Link: https://sg.run/RozO