Bare Excepts

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jan 2 19:30:03 EST 2010


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


> (This is a somewhat stupid example strictly for illustration.  A better
> and more-elaborate example would be something like trying to copy a file
> to fname and rename an existing file to '.bak' if it exists.  The tricky
> part would be trying to rename the '.bak' to fname if the copy fails.
> And yes, that's exactly what some code I wrote a few days ago does.)

Sounds interesting and useful. Would you care to share it with us, or to 
publish it as a recipe?



-- 
Steven



More information about the Python-list mailing list