我正在使用win32Com模块将数据写入使用Python 3.5的Windows 7计算机上的Excel工作表。当它运行时,我得到一个错误。我尝试了一个“try/except”块,但我尝试的错误类型显然不是实际的错误类型。这里是我的代码:确定错误/异常类型Python
import win32com.client as win32
import sqlite3
def writeWords(storage):
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1')
i = 0
storLen = len(storage)
while i < storLen:
varX = storage[i]
lenVar = len(varX)
q = 0
while q < lenVar:
tarf = str(storage[i][q].encode('ascii', errors='ignore')).lstrip("b\'").rstrip("\'")
try :
ws.Cells(q+1,i+1).Value = (tarf)
except pywintypes.com_error:
print("Error")
q +=1
q += 1
i += 1
回溯我得到的是这样的:
Traceback (most recent call last):
File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 65, in writeWords
ws.Cells(q+1,i+1).Value = (tarf)
File "C:\Users\LewTo002\AppData\Local\Programs\Python\Python35\lib\site-packages\win32com\client\__init__.py", line 474, in __setattr__
self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146777998), None)
在处理上述异常,另一个异常:
Traceback (most recent call last):
File "C:\Users\LewTo002\AppData\Local\Programs\Python\Python35\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec(codeObject, __main__.__dict__)
File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 100, in <module>
writeWords(storage)
File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 66, in writeWords
except pywintypes.com_error:
NameError: name 'pywintypes' is not defined
我习惯看到的东西像这里(https://docs.python.org/2/library/exceptions.html#exception-hierarchy),并一直基于我的写作方法/这里除外(https://docs.python.org/3/tutorial/errors.html)
我的问题是我如何根据追踪的顶部来确定我试图捕获的错误类型?
你能证明你的进口吗? –
听起来像你没有导入'pywintypes'。 – user2357112
我已将我的导入添加到主帖子中。你是正确的,我没有导入pywintypes。我会导入并重试,看看会发生什么。感谢user235! –