flake8-simplify
flake8-simplify copied to clipboard
[New Rule] Use `Path`s for reading and writing files
Explanation
Using Path
s requires much less code, particularly if Path
s are already being used to represent paths. The necessary methods were added in Python 3.5, so shouldn’t be a backwards-compatibility concern.
Example
# Bad
with open("foo.txt") as f:
text = f.read()
with open("bar.txt") as f:
f.write(text)
with open("baz.png", "rb") as f:
data = f.read()
with open("foobar.png", "wb") as f:
f.write(data)
# Good
from pathlib import Path
text = Path("foo.txt").read_text()
Path("bar.txt").write_text(text)
data = Path("baz.png").read_bytes()
Path("foobar.png").write_bytes(data)
There is a separate plugin just for that: https://gitlab.com/RoPP/flake8-use-pathlib