[Python-ideas] Add create mode to open()

Steven D'Aprano steve at pearwood.info
Wed Aug 17 03:41:32 CEST 2011


Guido van Rossum wrote:
> On Tue, Aug 16, 2011 at 5:12 PM, Bruce Leban <bruce at leapyear.org> wrote:

>> I didn't say never overwrite. What I don't like is programs overwriting
>> files without explicitly intending to do that.
> 
> Ah, but when you write open(fn, 'w') you *do* explicitly intend to
> overwrite. That's what it does.

No. I rarely intend to over-write an existing file. Usually I intend to 
create a new file. So I nearly always do this:

if not os.path.exists(fn):
     open(fn, 'w')

in the full knowledge that there's a race condition there, and that if I 
have multiple processes writing to files at the same time, as I often 
do, I could very well lose data.

And don't think for one second I'm even close to happy about that, but 
at least it is *some* protection, even if not very much.


>> Yes, there's a long legacy of overwriting files without warning or intent. I
>> suppose I'm fighting an uphill battle (and it's not my highest priority
>> complaint about bad code for that matter).
> 
> Right.

I'm not sure that a "create" mode is the right solution, but I am sure 
that, just like Bruce, I want a good, battle-hardened, standard, 
platform independent (as much as possible) solution to the above race 
condition bug. Perhaps it should be a module, like the tempfile module.

(There's a thread about adding something like this to shutil.)



-- 
Steven




More information about the Python-ideas mailing list