在openpyx中关闭文件

2024-04-19 15:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这两个过程都不像阅读文件时所期望的那样:

worksheet.close()
workbook.close()

有没有办法在openpyxl中关闭文件?还是程序退出时自动处理?我不想把电子表格留在记忆里。


Tags: 文件程序close过程电子表格workbook办法记忆里
1条回答
网友
1楼 · 发布于 2024-04-19 15:09:21

好吧,你可以看看源代码,Im目前使用的是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工作簿读入内存,进行更新,如果不保存它,更改可能会丢失,如果保存它,则在写入后关闭该文件。

Is there a way to close files once done in openpyxl? Or is it handled automatically when the program quits? I dont want to leave spreadsheets left hanging in memory.

您可以使用wb.save(filename = dest_filename)保存您的更改,例如handled automatically在读取或写入文件时,在操作后关闭它,但如果openpyxl自动保存您的更改,则class Workbook(object):没有__del__则在删除或垃圾收集该对象时不会调用任何内容,同样,这是为了1.5.5当前版本是1.5.8截至本文撰写之时,我怀疑已经发生了很大的变化。

相关问题 更多 >