[Python-ideas] `to_file()` method for strings
Andrew Barnert
abarnert at yahoo.com
Wed Mar 23 03:51:56 EDT 2016
On Mar 22, 2016, at 21:40, Alexander Belopolsky <alexander.belopolsky at gmail.com> wrote:
>
>
>> On Wed, Mar 23, 2016 at 12:33 AM, Chris Angelico <rosuav at gmail.com> wrote:
>> >> with tempfile.NamedTemporaryFile('w', dir=os.path.dirname(path),
>> ..
>> It's specifically selecting a directory for the temp file, so it ought
>> to work.
>
>
> I did not notice this. Thanks, Chris. Still not all filesystems do rename atomically.
That's why I used os.replace, not os.rename. Which _is_ guaranteed to either replace atomically or do nothing and fail (and works with the most important filesystems on Windows 2003+ and every major POSIX OS). So that's not the problem either.
The "delete=False" is also not a problem.
Doing the replace inside the NamedTemporaryFile may be a problem on Windows. Or maybe it was doing it right after a flush without something else in between? I forget. Whatever it is, I have a solution in the library that I use (which also emulates os.replace on Python 2.6-7 and 3.1-2), so I don't have to remember how to solve it every time.
One argument against adding it to write_file (besides the argument that novices don't discover pathlib and experts don't use it for other reasons) is that I think the one obvious way to do it should be atomic by default for novices, but that would be a breaking API change to the pathlib function. But if that were the way to get atomic writes in the stdlib, I'd start using pathlib for them.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160323/44b24a32/attachment.html>
More information about the Python-ideas
mailing list