The module pathlib was long overdue and continues to improve, though it still doesn’t fill all the gaps. But one unexpected boon from it is NOT a consolidation of another module’s functions but the addition of read and write functions that eliminate the need for the “with” structure and/or the “close” command. Most of us will initially stick with the concrete path options so we will import using “from pathlib import Path as p”. OK, you may not like the “as p” part but I do. So I stuff the “pathlib.Path” into”p”. I most frequently deal with one text file at a time so if I have a text file of names, I like to take a text file with a name like “contacts name file” and assign it to a variable, like “names” with
names = p(“contacts name file”)
or if you don’t use p it would be
pathlib.Path(“contacts name file”),
not really pythonic but once explained you get the gist.
The pathlib.Path methods .read_text and .write_text, when called, open the file, do their business, and then close the file. WALA – no more “with”, no more “close”.
names.write_text(“Mr. Jack Beanstalk”) kaboom, that’s it, all done.