aahz at pythoncraft.com
Thu Jan 14 22:33:38 CET 2010
In article <034fd208$0$1277$c3e8da3 at news.astraweb.com>,
Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> 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):
>> f = open(fname, 'rb')
>> data = f.read()
>> return data
>> except IOError:
>> logger.error("Can't read: %s", fname) return ''
>> f = open(fname, 'wb')
>> 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.
True; nevertheless, my point remains that if you want to do something
different depending on whether the file exists, you must use both LBYL
>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".
IIUC, you can lock files that don't 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?
Unfortunately, it's a bit too tightly tied to some other stuff in the
code, plus I'll need to get permission from my bosses. We'll see.
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur." --Red Adair
More information about the Python-list