Reputation: 1971
I am creating a new nested directory (data_dir = 'parent\child'
) 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
?
Upvotes: 3
Views: 6856
Reputation: 41116
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).
Upvotes: 7
Reputation: 147
In addition to CristiFati-s solution, a better way to avoid magic numbers, would be using the winerror of the pywin32 module:
import winerror
try:
os.mkdir(path)
except WindowsError as e:
if e.winerror == winerror.ERROR_PATH_NOT_FOUND:
print("Handling WindowsError 3")
elif e.winerror == winerror.ERROR_FILENAME_EXCED_RANGE:
print("Handling WindowsError 206")
else:
print("Handling other WindowsError")
except:
print("Handling other exceptions")
Upvotes: 3