使用openpyxl新建workbook并执行操作,在从某文件目录load workbook时,报错zipfile.BadZipFile: File is not a zip file
Traceback (most recent call last):
File "*.py", line 49, in *
wb = load_workbook(filename)
File "/home/*/.local/lib/python3.6/site-packages/openpyxl/reader/excel.py", line 316, in load_workbook
data_only, keep_links)
File "/home/*/.local/lib/python3.6/site-packages/openpyxl/reader/excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "/home/*/.local/lib/python3.6/site-packages/openpyxl/reader/excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "/usr/lib/python3.6/zipfile.py", line 1131, in __init__
self._RealGetContents()
File "/usr/lib/python3.6/zipfile.py", line 1198, in _RealGetContents
raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
出现错误的直接原因是,试图打开一个之前没有close的表格文件。这项错误操作可能是因为这些原因引起的:
也有可能是其他错误,但是不重要,看解决方法,可以从根源上避免这一类关于load/save的错误。
在写代码的时候一定要未雨绸缪,用安全的方式打开和退出excel文件,就可以从根源上避免上面的这一类关于load/save的错误。
安全地打开excel
打开文件时,用以下方式打开excel:如果已经存在原文件,就直接load;如果不存在,就新建workbook准备最后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()
安全地保存为excel
wb.save(filename) # 对需要保存写入内容的workbook
wb.close() # 对程序中只读的workbook
python编辑已存在的excel坑: BadZipFile: File is not a zip file