What is the most elegant way to open a file such that
As far as I can tell, the open
builtin doesn't seem up to the task: it provides various modes, but every one I tried fails to satisfy at least one of my requirements:
r+
fails if the file does not exist.w+
will truncate the file, losing any existing content.a+
will force all writes to go to the end of the file, at least on my OS X.Checking for the existence prior to opening the file feels bad since it leaves room for race conditions. The same holds for retrying the open with a different mode from within an exception handler. I hope there is a better way.
You need to use os.open()
to open it at a lower level in the OS than open()
allows. In particular, passing os.O_RDWR | os.O_CREAT
as flags
should do what you want. See the open(2)
man page for details. You can then pass the returned FD to os.fdopen()
to get a file object from it.