zak*_*191 7 python file openpyxl
这些过程都没有,正如预期的那样阅读文档:
worksheet.close()
workbook.close()
有没有办法在openpyxl中完成后关闭文件?或者在程序退出时自动处理?我不想让电子表格留在内存中.
Sam*_*lar 17
你可以看一下源代码,我目前正在使用1.5.5
def load_workbook(filename, use_iterators=False):        
    if isinstance(filename, file):
        # fileobject must have been opened with 'rb' flag
        # it is required by zipfile
        if 'b' not in filename.mode:
            raise OpenModeError("File-object must be opened in binary mode")
    try:
        archive = ZipFile(filename, 'r', ZIP_DEFLATED)
    except (BadZipfile, RuntimeError, IOError, ValueError), e:
        raise InvalidFileException(unicode(e))
    wb = Workbook()
    if use_iterators:
        wb._set_optimized_read()
    try:
        _load_workbook(wb, archive, filename, use_iterators)
    except KeyError, e:
        raise InvalidFileException(unicode(e))
    finally:
        archive.close()
    return wb
当我们加载工作簿时,它看起来是肯定关闭了存档,我们何时保存它?
  def save(self, filename):
    """Write data into the archive."""
    archive = ZipFile(filename, 'w', ZIP_DEFLATED)
    self.write_data(archive)
    archive.close()
它看起来像我们保存它时也会关闭存档.
从根本上我们将一个excel工作簿从一个文件中读入内存,然后关闭,进行更新,如果我们不保存它,可能会丢失更改,如果我们保存它,文件在写入后关闭.
有没有办法在openpyxl中完成后关闭文件?或者在程序退出时自动处理?我不想让电子表格留在内存中.
您可以在读取或写入文件时使用wb.save(filename = dest_filename)as 保存更改,handled automatically然后在操作后关闭它,但是让openpyxl自动保存您的更改,然后没有那个class Workbook(object):没有,__del__那么当该对象被删除或垃圾收集时,没有任何东西被调用对于1.5.5当前版本来说,1.5.8截至本文撰写时,我怀疑已经发生了很大的变化.