[Python-ideas] `to_file()` method for strings
Alexander Belopolsky
alexander.belopolsky at gmail.com
Wed Mar 23 00:22:49 EDT 2016
On Tue, Mar 22, 2016 at 11:33 PM, Andrew Barnert via Python-ideas <
python-ideas at python.org> wrote:
> Anyway, another huge advantage of this proposal is that it can handle
> atomic writes properly. After all, even novices can quickly learn this:
>
> with open(path, 'w') as f:
> f.write(s)
>
> ... but how many of them can even understand this:
>
> with tempfile.NamedTemporaryFile('w', dir=os.path.dirname(path),
> delete=False) as f:
> f.write(s)
> f.flush()
> os.replace(f.path, path)
>
This would be a reasonable addition as a pathlib.Path method.
>
> (That's assuming I even got the latter right. I'm on my phone right now,
> so I can't check, but I wouldn't be surprised if there's a mistake there...)
>
You've got it wrong, but I understand what you tried to achieve. Note that
the "write to temp and move" trick may not work if your /tmp and your path
are mounted on different filesystems. And with some filesystems it may not
work at all, but I agree that it would be nice to have a state of the art
atomic write method somewhere in stdlib.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160323/17fbd4a2/attachment.html>
More information about the Python-ideas
mailing list