捕获特定的“Windows Error”编号 - python

Sup*_*cia 3 python windows exception

我正在data_dir = 'parent\child'python 中创建一个新的嵌套目录 ( ):

try:
    os.mkdir(data_dir)
except WindowsError:
    pass   
Run Code Online (Sandbox Code Playgroud)

如果父目录'parent'不存在(但是,因为我可能稍后在代码中进行设置),则代码将其捕获为 aWindows Error 3并继续前进。

然而,现在也可能发生的情况是Windows Error 206文件名或扩展名太长。为此我需要采取单独的行动。


有没有一种方法可以区分Windows Error 3and 206(和其他)以便提高 unique Exceptions

Cri*_*ati 7

您可以使用WindowsError.winerror(继承自OSError : [Python.Docs]: 内置异常 - winerror)来区分底层错误。就像是:

>>> def create_dir(path):
...     try:
...         os.mkdir(path)
...     except WindowsError as e:
...         if e.winerror == 3:
...             print("Handling WindowsError 3")
...         elif e.winerror == 206:
...             print("Handling WindowsError 206")
...         else:
...             print("Handling other WindowsError")
...     except:
...         print("Handling other exceptions")
...
>>>
>>> create_dir("not/existing")
Handling WindowsError 3
>>> create_dir("a" * 228)
Handling WindowsError 206
>>> create_dir(":")
Handling other WindowsError
Run Code Online (Sandbox Code Playgroud)

当然,使用[Python.Docs]: os.makedirs(name, mode=0o777, exit_ok=False)可以轻松避免WindowsError 3