flake8-simplify icon indicating copy to clipboard operation
flake8-simplify copied to clipboard

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

Open TomFryers opened this issue 2 years ago • 1 comments

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)

TomFryers avatar Mar 06 '22 15:03 TomFryers

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

gladykov avatar May 10 '22 01:05 gladykov