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

Chris Angelico rosuav at gmail.com
Wed Mar 23 00:33:15 EDT 2016


On Wed, Mar 23, 2016 at 3:22 PM, Alexander Belopolsky
<alexander.belopolsky at gmail.com> wrote:
>
> On Tue, Mar 22, 2016 at 11:33 PM, Andrew Barnert via Python-ideas
> <python-ideas at python.org> wrote:
>>     with tempfile.NamedTemporaryFile('w', dir=os.path.dirname(path),
>> delete=False) as f:
>>         f.write(s)
>>         f.flush()
>>         os.replace(f.path, path)
> 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.

It's specifically selecting a directory for the temp file, so it ought
to work. However, I'm not certain in my own head of the interaction
between NamedTemporaryFile with delete=False and os.replace (nor of
exactly how the latter differs from os.rename); what exactly happens
when the context manager exits here? And what happens if there's an
exception in the middle of this and stuff doesn't complete properly?
Are there points at which this could (a) destroy data by deleting
without saving, or (b) leave cruft around?

This would be very nice to have as either stdlib or a well-documented recipe.

ChrisA


More information about the Python-ideas mailing list