Python and Exception Handling IOError I'm trying to work with exception handling by displaying "No Such File" when the file doesn't exist.  I need to use a try statement.

import sys

try:
   f = open("h:\\nosuchdirectory\\nosuchfile.txt","w") # do not modify this line
    f.write("This is the grape file") # do not modify this line
    f.close() # do not modify this line

except IOError:
    print ("No Such File")


Started with:

f = open("h:\\nosuchdirectory\\nosuchfile.txt","w") # do not modify this line
f.write("This is the grape file") # do not modify this line
f.close() # do not modify this line
This is actually an interesting question.

@RuslanOsipov has provided a solution, but technically it is vulnerable to a time-of-check vs. time-of-use race condition.  In other words, there is a brief window between the isfile() call and the open() call where a things could go wrong.  Depending on the application, that could even be considered a security vulnerability.

So, what to do?  For the full story, read Python Issue 12760.  In Python 3.3, open() gained an 'x' mode flag that makes it behave like the code in this question wants it to.  For older versions of Python that lack the 'x' flag, the workaround is:

def create(file):
    fd = os.open(file, os.O_EXCL | os.O_CREAT | os.O_WRONLY)
    return os.fdopen(fd)