Steven D'Aprano wrote:
On Sat, 02 Jan 2010 09:40:44 -0800, Aahz wrote:

OTOH, if you want to do something different depending on whether the
file exists, you need to use both approaches:

if os.path.exists(fname):
    try:
        f = open(fname, 'rb')
        data = f.read()
        f.close()
        return data
    except IOError:
        logger.error("Can't read: %s", fname) return ''
else:
    try:
        f = open(fname, 'wb')
        f.write(data)
        f.close()
    except IOError:
        logger.error("Can't write: %s", fname)
    return None

Unfortunately, this is still vulnerable to the same sort of race condition I spoke about.

Even more unfortunately, I don't know that there is any fool-proof way of avoiding such race conditions in general. Particularly the problem of "open this file for writing only if it doesn't already exist". <snip>
In Windows, there is a way to do it. It's just not exposed to the Python built-in function open(). You use the CreateFile() function, with /dwCreationDisposition/ of CREATE_NEW.

It's atomic, and fails politely if the file already exists.

No idea if Unix has a similar functionality.

DaveA


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to