Closing files in openpyxl

zakparks31191 picture zakparks31191 · Jun 26, 2012 · Viewed 33.5k times · Source

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.

Answer

Samy Vilar picture Samy Vilar · Jun 26, 2012

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.