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:
JavaScript121211>>> def create_dir(path):
2try:
3os.mkdir(path)
4except WindowsError as e:
5if e.winerror == 3:
6print("Handling WindowsError 3")
7elif e.winerror == 206:
8print("Handling WindowsError 206")
9else:
10print("Handling other WindowsError")
11except:
12print("Handling other exceptions")
1314>>>
15>>> create_dir("not/existing")
16Handling WindowsError 3
17>>> create_dir("a" * 228)
18Handling WindowsError 206
19>>> create_dir(":")
20Handling other WindowsError
21
Of course, WindowsError 3 can easily be avoided, using [Python.Docs]: os.makedirs(name, mode=0o777, exist_ok=False).