Python openpyxl excel open zipfile error resolution: zipfile.BadZipFile: File is not a zip file

Error description

The immediate cause of the error is trying to open a table file that was not previously closed. This error could be caused by:

In the process before

  • the workbook that was opened did not have a normal close, resulting in additional temporary files, and errors occurred when trying to open these temporary files; The workbook before
  • did not overwrite the existing files when saving.

can also be other errors, but it doesn’t matter, look at the solution, you can from the root to avoid this kind of error about load/save .

solution

open and exit excel files in a safe way, you can avoid the above type of load/save error. When opening a file, open excel in the following ways: if the original file already exists, just load it directly; If it doesn’t exist, create a new workbook and prepare the last save.

import os
from openpyxl import Workbook
from openpyxl import load_workbook
if os.path.exists(new_filename):
    new_wb = load_workbook(new_filename)
else:
    new_wb = Workbook()

is safely saved as excel

  • first, remember to exit as soon as you run out of files. Second, when exiting a file, for all workbooks, if you need to save, if you don’t need to save (read-only), be sure to close
wb.save(filename) # For workbooks that need to save written content
wb.close() # Read-only workbook for the program

Read More: