pythonfile-iopython-3.xioposix

Open file for read/write, create if needed


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:

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.


Solution

  • 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.