1 year ago
#231453
cornhenge
Trapping Permission Error when opening workbook with openpyxl
I have an application that interacts with xlsx workbooks using openpyxl. It is possible for users to have the needed workbook open in Excel when the program runs, throwing a FilePermission Error. There seem to be two issues
(ISSUE 1) the following:
try:
wbTarget = load_workbook(filename='%s' % (strfileTarget))
except PermissionError:
print("Please close the file")
break
throws a "SyntaxError: 'break' outside loop" error. This is weird given the same pattern is used in other situations (such as trapping'None' during xlsx processing) without problem. So the question for this issue is, Can someone please explain why the break is not working here?
(ISSUE 2) Instead of the break, the 'print' line below would be substituted for a tk.messagebox.showerror to tell the user to close the file and then continue or quit the program, but... i have to catch the exception first, so here is what i tried:
try:
wbTarget = load_workbook(filename='%s' % (strfileTarget))
except PermissionError:
print("Please close the file")
this does not trap the "PermissionError: [Errno 13] Permission denied:" error. From research it also appears the exception might be an 'IOError'. Changing to 'IOError' still throws the same error instead of trapping it.
finally, i just tried to catch 'any ol' exception with 'exception:' and omitting the exception type. but error is still not trapped when the program is run.
try:
wbTarget = load_workbook(filename='%s' % (strfileTarget))
except:
print("Please close the file")
So the question for this issue is, how is the file permission issue trapped?
python
openpyxl
ioerror
permissionerror
0 Answers
Your Answer