Skip to content
Advertisement

Catch a specific `Windows Error` number – python

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

JavaScript

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:

JavaScript

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