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

Antoine Pitrou solipsis at pitrou.net
Wed Aug 17 11:43:36 CEST 2011


On Wed, 17 Aug 2011 13:42:59 +1000
Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Wed, Aug 17, 2011 at 12:10 PM, Calvin Spealman <ironfroggy at gmail.com> wrote:
> > While there are plenty of responders debating how unix-y or sensible
> > this is from the standpoint of other languages or precedents, I think
> > this makes sense from the standpoint of new users and a fresh
> > viewpoints. Creating a new file is a very sensible thing to want in a
> > single operation.
> 
> Yes, this suggestion came out of the shutil.move discussion, precisely
> *because* it is so hard to write a platform-independent, multi-process
> safe operation that will reliably either create a new file or else
> throw an exception if the file already exists,

Platform-independent is not hard. O_EXCL is specified by POSIX:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html

Works under Linux:

>>> import os
>>> os.open("LICENSE", os.O_CREAT | os.O_EXCL)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'LICENSE'

Works under Windows:

>>> import os
>>> os.open("LICENSE", os.O_CREAT | os.O_EXCL)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists

(yes, I'm taking the opportunity to showcase PEP 3151)

Regards

Antoine.





More information about the Python-ideas mailing list