Skip to content
Advertisement

Catch a specific `Windows Error` number – python

I am creating a new nested directory (data_dir = 'parentchild') in python:

try:
    os.mkdir(data_dir)
except WindowsError:
    pass   

If the parent directory 'parent' did not exists (yet, ’cause I might be setting later in the code), then the code caught that as a Windows Error 3 and moved on.

However now what could also happen is Windows Error 206 which is when the filename or extension is too long. For which I would need to take a separate action.


Is there a way to distinguish between Windows Error 3 and 206 (and others) so as to raise distinct Exceptions?

Advertisement

Answer

You could use WindowsError.winerror (inherited from OSError: [Python.Docs]: Built-in Exceptions – winerror) to differentiate between underlying errors. Something like:

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

Of course, WindowsError 3 can easily be avoided, using [Python.Docs]: os.makedirs(name, mode=0o777, exist_ok=False).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement