Search code examples
pythonattributeerrorwith-statement

with statement python __enter__ attribute error


This :

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 this:

      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__

Tried this:

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.

Edit:

Apparently closing the excel fixes it, and the with statement is not needed.

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

Solution

  • from openpyxl documentation

    Read an existing workbook:

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

    This is an example on how to use the load_workbook method, so you don't need to use that with statement. Just use assignment.

    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