[Python-ideas] Add pathlib.Path.write_json and pathlib.Path.read_json
Steven D'Aprano
steve at pearwood.info
Mon Mar 27 11:04:29 EDT 2017
On Mon, Mar 27, 2017 at 02:50:38PM +0200, Ram Rachum wrote:
> Hi guys,
>
> What do you think about adding methods pathlib.Path.write_json and
> pathlib.Path.read_json , similar to write_text, write_bytes, read_text,
> read_bytes?
>
> This would make writing / reading JSON to a file a one liner instead of a
> two-line with clause.
Reading/writing JSON is already a one liner, for people who care about
writing one liners:
obj = json.load(open("foo.json"))
json.dump(obj, open("foo.json"))
Pathlib exists as an OO interface to low-level path and file operations.
It understands how to read and write to files, but it doesn't understand
the content of those files. I don't think it should.
Of course pathlib can already read JSON, or for that matter ReST text
or JPG binary files. It can read anything as text or bytes, including
JSON:
some_path.write_text(json.dumps(obj))
json.loads(some_path.read_text())
I don't think it should be pathlib's responsibility to deal with the
file format (besides text). Today you want to add JSON support. What
about XML and plists and ini files? Tomorrow you'll ask for HTML
support, next week someone will want pathlib to support .wav files as a
one liner, and before you know it pathlib is responsible for a hundred
different file formats with separate read_* and write_* methods.
That's not pathlib's responsibility, and there is nothing wrong with
writing two lines of code.
--
Steve
More information about the Python-ideas
mailing list