How to catch a pywin32com exception on opening files

主宰稳场 提交于 2019-12-25 08:57:40

问题


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

回答1:


Try:

from pythoncom import com_error

and catch it in your except block



来源:https://stackoverflow.com/questions/6336831/how-to-catch-a-pywin32com-exception-on-opening-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!