correct way to catch exception with Python 'with' statement

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Nov 29 22:20:31 EST 2016


On Wednesday 30 November 2016 10:59, woooee at gmail.com wrote:

> If you want to do something only if the file exists (or does not), use
> os.path.isfile(filename)

No, don't do that. Just because the file exists, doesn't mean that you have 
permission to read or write to it.

Worse, the code is vulnerable to race conditions. Look at this:

if os.path.isfile(filename):
    with open(filename) as f:
        process(f)


Just because the file exists when you test it, doesn't mean it still exists a 
millisecond later when you go to open the file. On a modern multi-processing 
system, like Windows, OS X or Linux, a lot can happen in the microseconds 
between checking for the file's existence and actually accessing the file.

This is called a "Time Of Check To Time Of Use" bug, and it can be a security 
vulnerability.



-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson




More information about the Python-list mailing list