我想隐式关闭类实例销毁的工作簿。 xlsxwriter.workbook.py方法说要明确地执行它然后它工作。 但是在每个Excel文件创建脚本结束时,我必须添加额外的行来关闭Workbook。有没有办法让它自动关闭?
import pandas as pd
import xlsxwriter
class ExcelFile():
def __init__(self, file_name):
self.writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
self.workbook = self.writer.book
def __del__(self):
self.workbook.close()
print('del')
脚本:
e = ExcelFile('test.xlsx')
# e.workbook.close() <--This works but I don't want this line
答案 0 :(得分:1)
您无法控制何时调用__del__
方法。已有关于SO的__del__
的大量信息,您可以搜索它(例如,https://stackoverflow.com/a/1481512/1453822)。
相反,我会使用上下文管理器:
class ExcelFile():
def __init__(self, file_name):
self.writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
self.workbook = self.writer.book
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
self.workbook.close()
with ExcelFile('test.xlsx') as e:
# do whatever with e
pass
输出将是:
'exit'
承诺在退出__exit__
块时调用 with ExcelFile(..)
,即使引发了异常:
with ExcelFile('test.xlsx') as e:
1/0
输出
Traceback (most recent call last):
File "main.py", line 57, in <module>
1/0
ZeroDivisionError: division by zero
exit