How to catch a pywin32com exception on opening files
Asked Answered
L

1

1

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
Lampkin answered 13/6, 2011 at 21:53 Comment(0)
B
2

Try:

from pythoncom import com_error

and catch it in your except block

Brader answered 13/6, 2011 at 22:0 Comment(1)
hi @Brader whats the difference between from pythoncom import com_error and from pywintypes import com_error. my question here:#62516709Eusebioeusebius

© 2022 - 2024 — McMap. All rights reserved.