问题
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