How to catch a pywin32com exception on opening files
I am trying to open an excel file in python us开发者_如何转开发ing 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
Try:
from pythoncom import com_error
and catch it in your except
block
精彩评论