繁体   English   中英

with 语句 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

返回这个:

      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() 语句,因此如果这不是您第一次运行代码,则很可能您没有正确关闭文件并且它仍然位于 memory 中并阻止使用权。

编辑:

显然关闭 excel 修复它

links_excel.close()

来自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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM