I am trying to understand exceptions with Python 2.7.6, on Windows 8.
Here's the code I am testing, which aims to create a new directory at My_New_Dir
. If the directory already exists, I want to delete the entire directory and its contents, and then create a fresh directory.
import os
dir = 'My_New_Dir'
try:
os.mkdir(dir)
except IOError as e:
print 'exception thrown'
shutil.rmtree(dir)
os.mkdir(dir)
The thing is, the exception is never thrown. The code works fine if the directory does not already exist, but if the directory does exist, then I get the error:
WindowsError: [Error 183] Cannot create a file when that file already exists: 'My_New_Dir'
But according to the Python documentation for os.mkdir(),
If the directory already exists, OSError is raised.
So why is the Windows error being thrown, rather than the Python exception?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…