4

こんにちは、

私は Python でいくつかの ETL スクリプトを作成しており、現在 win32com.client を使用して Excel でいくつかのデータ接続を開いて更新しています。

私の質問はこれです: 「Excel.Application」自体を開閉するためにwithステートメントを使用する必要がありますか?

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__

または、close コマンドを明示的に呼び出す必要がありますか

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')

2 番目の例は、私が使用してきたもので、動作します。上記の関数をスクリプト化するためのよりpythonicな方法は何だろうと思っているだけだと思います。

(fyi - 初めての質問者、長年の読者)

4

1 に答える 1

3

はcontext managerではないため、AttributeError: __enter__エラーが発生するため、ステートメントをサポートしていません。xl.workbooks.openwith

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 に答える