Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

python - Closing files in openpyxl

Neither of these process, as would be expected reading the documentation:

worksheet.close()
workbook.close()

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...