with statement python __enter__ 属性错误

with statement python __enter__ attribute error

这个:

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

returns这个:

      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__

试过这个:

You're not using with statement and there's no close() statement so if this is not the first time you're running the code, it's likely that you haven't closed the file properly and it is still sitting in the memory and prevents access.

编辑:

显然关闭 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()

来自 openpyxl documentation

读取现有工作簿:

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