4

下午好,

我正在用 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 方式是什么。

(仅供参考 - 第一次提问,长期读者)

4

1 回答 1

3

您收到AttributeError: __enter__错误是因为xl.workbooks.openis not a context manager,因此它不支持该with语句。

如果要with在代码中使用语句,可以使用标准库中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当块中的代码完成执行时,将自动调用close传递给它的对象。with

于 2018-11-18T09:47:45.260 回答