打开相同文件时出现问题 openpyxl

Having problem with opening same files openpyxl

正在编写一个程序,将文件中的内容打乱。所有文件几乎相同,但对其中一些文件不起作用。看不懂。

for file in allFiles:
print(file)
items = []
fileName = file
fileIndex = 1
directory = os.path.join(path, fileName[:-5].strip())
if not os.path.exists(directory):
    os.mkdir(directory)
    
theFile = openpyxl.load_workbook(file)
allSheetNames = theFile.sheetnames

在一些文件之后,它向我显示了这些错误:

Traceback (most recent call last):
  File "D:\staff\Python\NewProject\glow.py", line 25, in <module>
    theFile = openpyxl.load_workbook(file)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\reader\excel.py", line 313, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\zipfile.py", line 1269, in __init__
    self._RealGetContents()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\zipfile.py", line 1336, in _RealGetContents
    raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file

但在此之前一切正常,没有错误。有人能猜到,为什么?谢谢大家。 以这种方式查找文件:

path = os.getcwd()
sourcePath = os.getcwd() + '\source'
extension = 'xlsx'
os.chdir(sourcePath)
allFiles = glob.glob('*.{}'.format(extension))

您遍历所有与文件类型无关的文件。可能是您或某个进程向目录中添加了一个文件,该文件不是 xlsx 文件。这就是openpyxl读取失败的原因。