下午好,
我正在用 Python 编写一些 ETL 脚本,目前正在使用 win32com.client 在 Excel 中打开和刷新一些数据连接。
我的问题是:我应该使用with语句来打开/关闭“Excel.Application”吗?
import win32com.client
xl = win32com.client.DispatchEx("Excel.Application")
def wb_ref(file):
xl.DisplayAlerts = False
with xl.workbooks.open(file) as wb:
wb.RefreshAll()
wb.Save()
wb_ref('C:/Users/smugs/Documents/folder_a/workbooks/test.xlsx')
当我尝试这个时会发生异常,所以我显然没有正确使用它。
Traceback (most recent call last):
File "C:/Users/smugs/Documents/Python Scripts/Work/km_jobs/utils/xl_conv.py", line 32, in <module>
wb_ref( 'C:/Users/smugs/Documents/folder_a/workbooks/test.xlsx')
File "C:/Users/smugs/Documents/Python Scripts/Work/km_jobs/utils/xl_conv.py", line 11, in wb_ref
with xl.workbooks.open(file) as wb:
AttributeError: __enter__
还是我需要显式调用关闭命令
def wb_ref(file):
xl.DisplayAlerts = False
wb = xl.workbooks.open(file)
wb.RefreshAll()
wb.Save()
wb.Close()
wb_ref('C:/Users/smugs/Documents/folder_a/workbooks/test.xlsx')
第二个例子是我一直在使用的,它有效。我想我只是想知道为上述函数编写脚本的更 Pythonic 方式是什么。
(仅供参考 - 第一次提问,长期读者)