MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
185 stars 19 forks source link

[New Rule] Use `Path`s for reading and writing files #111

Open TomFryers opened 2 years ago

TomFryers commented 2 years ago

Explanation

Using Paths requires much less code, particularly if Paths 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)
gladykov commented 2 years ago

There is a separate plugin just for that: https://gitlab.com/RoPP/flake8-use-pathlib