如何捕获打开文件时的 pywin32com 异常
我正在尝试使用 COM 在 python 中打开一个 excel 文件,并尝试捕获文件未找到错误:
我首先尝试捕获 IOError:
try:
output = xl.Workbooks.Open(Params.workbookName)
except IOError as reason:
print reason
exit()
但是 COM 在出现文件未找到问题时不会引发 IO 错误,而是它引发称为 com_error 的错误:
com_error: (-2147352567, '异常 发生了。', (0, u'Microsoft Office Excel', u"'asdf.xlsx' 不能 成立。检查文件的拼写 名称,并验证该文件 位置正确。\n\n如果您是 尝试从您的列表中打开该文件 最近使用的文件,请确保 该文件尚未重命名, 移动或删除。”,u'C:\Program 文件 (x86)\Microsoft 办公室\Office12\1033\XLMAIN11.CHM', 0、-2146827284)、无)
所以从逻辑上我尝试了这个:
try:
output = xl.Workbooks.Open(Params.workbookName)
except com_error as reason:
print reason
exit()
但是......
NameError: global name 'ComError' is not defined
I am trying to open an excel file in python using COM, and trying to catch the file not found error:
I first tried catching the IOError:
try:
output = xl.Workbooks.Open(Params.workbookName)
except IOError as reason:
print reason
exit()
But COM doesn't raise an IO Error when it has a file not found problem, instead it raises something called com_error:
com_error: (-2147352567, 'Exception
occurred.', (0, u'Microsoft Office
Excel', u"'asdf.xlsx' could not be
found. Check the spelling of the file
name, and verify that the file
location is correct.\n\nIf you are
trying to open the file from your list
of most recently used files, make sure
that the file has not been renamed,
moved, or deleted.", u'C:\Program
Files (x86)\Microsoft
Office\Office12\1033\XLMAIN11.CHM',
0, -2146827284), None)
so logically I tried this:
try:
output = xl.Workbooks.Open(Params.workbookName)
except com_error as reason:
print reason
exit()
but...
NameError: global name 'ComError' is not defined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
并在您的
except
块中捕获它Try:
and catch it in your
except
block