Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

windows - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...