quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.72k stars 249 forks source link

Not using with to open files - what about pathlib's read_text #139

Open DanGolding opened 4 years ago

DanGolding commented 4 years ago

Regarding the anti-pattern of not using with to open files, if you are reading the entire contents of the file in one shot as in the examples, you can use read_text from pathlib which opens and closes the file for you internally. So it isn't always an anti-pattern to not use a context manager for reading text/bytes, in fact I would argue that

with open("file.txt", "r") as f:
    content = f.read()

is an anti-pattern for

content  = Path("file.txt").read_text()
abhijeetmote commented 4 years ago

Hi @DanGolding I have done this, please let me know If I need to change anything. This is my first commit to this repo https://github.com/quantifiedcode/python-anti-patterns/pull/140

DanGolding commented 4 years ago

Hi @DanGolding I have done this, please let me know If I need to change anything. This is my first commit to this repo

140

Looks good, thanks :) , left a couple of comments.