Python: Getting a WindowsError instead of an IOError

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?


WindowsError is a subclass of OSError . From the exceptions documentation:

Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value. The winerror and strerror values are created from the return values of the GetLastError() and FormatMessage() functions from the Windows Platform API. The errno value maps the winerror value to corresponding errno.h values. This is a subclass of OSError .

You are trying to catch IOError however, which is not such a parent class of WindowsError ; as a result it won't suffice to catch either OSError nor WindowsError .

Alter your code to use the correct exception here:

try:
    os.mkdir(dir)
except OSError as e:

or use WindowsError ; this would tie your code to the Windows platform.


You mis-read it. It is "OSError" not "IOError", and WindowsError is a subclasss of "OSError" for your specific working OS.

>>> issubclass(WindowsError, OSError)
True

Besides, for your propose, this API is better:

os.path.isdir(path): Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.

if os.path.isdir(dir):
    shutil.rmtree(dir)
os.mkdir(dir)

If you search for "WindowsError" on the exceptions page, you will see that WindowsError is in fact a Python exception. It is a subclass of OSError , so the documentation is still correct. If you change to

try:
    os.mkdir(dir)
except OSError as e:
    print 'exception thrown'
    shutil.rmtree(dir)
    os.mkdir(dir)

then you will catch the exception.

链接地址: http://www.djcxy.com/p/83742.html

上一篇: 在移动IE上禁用标注(上下文菜单)

下一篇: Python:获取WindowsError而不是IOError