在openpyxl中关闭文件 [英] Closing files in openpyxl
问题描述
这两个过程都不是,正如阅读文档所期望的那样:
Neither of these process, as would be expected reading the documentation:
worksheet.close()
workbook.close()
一旦在openpyxl中完成操作,是否有办法关闭文件?还是在程序退出时自动处理?我不想让电子表格挂在内存中.
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.
推荐答案
好吧,您可以看一下源代码,Im目前正在使用1.5.5
well you can take a look at the source code, Im currently using 1.5.5 as such
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
好像是的,它确实关闭了存档,当我们加载工作簿时,如何保存它呢?
it looks like yes it does close the archive, when we load a workbook, how about when we save it?
def save(self, filename):
"""Write data into the archive."""
archive = ZipFile(filename, 'w', ZIP_DEFLATED)
self.write_data(archive)
archive.close()
当我们保存档案时,它似乎也会关闭档案.
it looks like it also closes the archive when we save it.
从根本上来说,我们从一个文件中读取一个excel工作簿,然后将其关闭,进行更新,如果不保存,则更改可能丢失,如果保存,则写入后文件将被关闭.
Fundamentally we read an excel workbook into memory from a file which is closed afterwards, make updates, if we don't save it, the changes presumably are lost, if we save it, the file is closed after writing.
一旦在openpyxl中完成操作,是否有办法关闭文件?还是在程序退出时自动处理?我不想让电子表格挂在内存中.
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自动保存更改,然后否是__del__
,那么当该对象被删除或垃圾回收时,什么也不会被调用,这还是1.5.5
的当前版本,在撰写本文时,我怀疑是1.5.8
.
you can save your changes using wb.save(filename = dest_filename)
as for handled automatically
when readin or writing to a file then yes its closed after operation but having openpyxl automatically save your changes then no being that class Workbook(object):
doesn't have __del__
then nothing is called when that object is deleted or garbage collected, again this is for 1.5.5
the current version is 1.5.8
as of this writing, I doubt to much has changed.
这篇关于在openpyxl中关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!