Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>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)
    return
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading