with语句python __enter__属性错误

问题描述 投票:0回答:2

这个:

def add_to_excel(list_to_save, file_to_save_in):

my_file = dir_path + '\\' + file_to_save_in
with openpyxl.load_workbook(filename=my_file) as links_excel:
    sheet = links_excel['Sheet1']
    for i in list_to_save:
        sheet.append(i)
    links_excel.save(filename)
    return

返回这个:

      3     my_file = dir_path + '\\' + file_to_save_in
----> 4     with openpyxl.load_workbook(filename=my_file) as links_excel:
      5         sheet = links_excel['Sheet1']
      6         for i in list_to_save:

AttributeError: __enter__

尝试过这个:

您没有使用 with 语句,也没有 close() 语句,因此如果这不是您第一次运行代码,则很可能您没有正确关闭文件,并且它仍然位于内存中,并且阻止访问。

编辑:

显然关闭Excel就可以修复它,并且不需要with语句。

links_excel.close()

def add_to_excel(list_to_save, file_to_save_in):

my_file = os.path.join(dir_path, file_to_save_in)
links_excel=openpyxl.load_workbook(filename=my_file)
sheet = links_excel['Sheet1']
for i in list_to_save:
    sheet.append(i)
links_excel.save(my_file)
links_excel.close()
python attributeerror with-statement
2个回答
1
投票

来自 openpyxl 文档

阅读现有的工作簿:

from openpyxl import load_workbook
wb = load_workbook(filename = 'empty_book.xlsx')
sheet_ranges = wb['range names']
print(sheet_ranges['D18'].value)

这是如何使用

load_workbook
方法的示例,因此您不需要使用 with 语句。只需使用分配即可。

def add_to_excel(list_to_save, file_to_save_in):
    
    my_file = dir_path + '\\' + file_to_save_in
    links_excel = openpyxl.load_workbook(filename=my_file) 
    sheet = links_excel['Sheet1']
    for i in list_to_save:
        sheet.append(i)
    links_excel.save(filename)
    links_excel.close()
    return

0
投票

接受的答案是绝对正确的。但是,仍然可以使用上下文管理器打开工作簿。通过实现一个小接口类:

class Workbook(object):
    def __init__(self, path):
        self.wb =  load_workbook(filename=path)

    def __enter__(self):
        return self.wb
    
    def __exit__(self, type, value, traceback):
        self.wb.close()

您可以将 openpyxl 工作簿实例与上下文管理器(with 语句)一起使用:

with Workbook(path) as wb:
    sheet = wb['Sheet1']
    for i in list_to_save:
        sheet.append(i)
    wb.save(filename)
© www.soinside.com 2019 - 2024. All rights reserved.