使用 openpyxl 打开工作簿时捕获权限错误
我有一个使用 openpyxl 与 xlsx 工作簿交互的应用程序。当程序运行时,用户可能会在 Excel 中打开所需的工作簿,从而引发 FilePermission 错误。似乎有两个问题
(问题 1)如下:
try:
wbTarget = load_workbook(filename='%s' % (strfileTarget))
except PermissionError:
print("Please close the file")
break
抛出“SyntaxError:‘break’外循环”错误。这很奇怪,因为在其他情况下使用相同的模式(例如在 xlsx 处理期间捕获“None”)没有问题。所以这个问题的问题是,有人可以解释一下为什么中断在这里不起作用吗?
(问题 2)下面的“打印”行将替换为 tk.messagebox.showerror,以告诉用户关闭文件,然后继续或退出程序,而不是中断,但是...我必须捕获首先是异常,所以这就是我尝试过的:
try:
wbTarget = load_workbook(filename='%s' % (strfileTarget))
except PermissionError:
print("Please close the file")
这不会捕获“PermissionError:[Errno 13]权限被拒绝:”错误。根据研究,异常可能是“IOError”。更改为“IOError”仍然会引发相同的错误,而不是捕获它。
最后,我只是尝试用“异常:”捕获“任何ol”异常并省略异常类型。但程序运行时仍然没有捕获错误。
try:
wbTarget = load_workbook(filename='%s' % (strfileTarget))
except:
print("Please close the file")
那么这个问题的问题是,文件权限问题是如何被困的呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论