python ioerror,Python:获取WindowsError而不是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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值