[Python-ideas] `to_file()` method for strings

Koos Zevenhoven k7hoven at gmail.com
Thu Mar 24 11:02:16 EDT 2016


On Wed, Mar 23, 2016 at 5:06 AM, Nick Eubank <nickeubank at gmail.com> wrote:

[...]

> Apparently there's something like this in the Path library
> (https://docs.python.org/dev/library/pathlib.html#pathlib.Path.write_text) ,
> but I suspect most people have no idea about that method (I've been doing
> python for years and this has always been a personal frustration, and I've
> asked several others for better options and no one had one to offer), and it
> seems like it would make much more sense as a string method. If someone has
> a string they want to save to disk, I can't imagine anyone looking in the
> Path library.
>

Maybe you know this, but Path.read_text and Path.write_text (and the
bytes versions) were introduced in Python 3.5, released only half a
year ago, so there has not really been time for their adoption.

 Path("mytextfile.txt").write_text(...)
 Path("mytextfile.txt").read_text()

Besides being very readable and convenient, one of the nice things
about this is that it helps avoid code like

 open("mytextfile.txt").write(text)

which you see all the time, even if the file will be left open for
some time after this in non-ref-counting implementations of Python.

So, as mentioned before by others, all we need is the better interplay
of pathlib with the rest of the stdlib and that people will learn
about it. Personally, I now always use `pathlib` instead of `open`
when I don't need to care about compatibility with old Python
versions. Maybe some day, Path could be in builtins like open is now?

 - Koos


More information about the Python-ideas mailing list