下午好
我正在用 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 方式是什么。
(仅供引用 - 首次提问者,长期读者)
最佳答案
您收到 AttributeError: __enter__
错误,因为 xl.workbooks.open
不是 context manager , 所以它不支持 with
语句。
如果您想在代码中使用with
语句,您可以使用closing来自 contextlib 的函数标准库中的模块,像这样:
from contextlib import closing
def wb_ref(file):
xl.DisplayAlerts = False
with closing(xl.workbooks.open(file)) as wb:
wb.RefreshAll()
wb.Save()
contextlib.closing
将在 with
block 中的代码完成执行时自动调用传递给它的对象的 close
。
关于Python win32com.client 和 "with"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355048/