我一直在尝试编写一个脚本来获取图像并将它们粘贴到一个文件中。为此,我使用ZipFile从zipfile中提取.bin图像文件,并计划使用openpyxl将它们粘贴到一个新的.xlsx文件中。
当我运行这个程序时,我最终得到一个KeyError:'. wmf'中找到。
我试着将图像类型转换为.png(或其他光栅图像类型)。这确实解决了这个问题,但.bin图像文件的行为似乎有点像矢量类型的图像,我想保留这个属性。
我很想知道如何解决这个问题,谢谢!
下面是我的代码:
from zipfile import ZipFile
from pathlib import Path
import sys
import os
import xlsxwriter as xw
"Function to find location of images"
imgformats = ('bin')
def is_image(filename):
return any(filename.endswith(ext) for ext in imgformats)
"Create folder"
folders = ['imgsave']
for folder in folders:
if not os.path.exists(folder):
os.makedirs(folder)
"Group the files"
path = Path(".")
try:
files = path.glob('*.xlsx')
except PermissionError as e:
print(f'Permission Error: {str(e)}')
sys.exit()
"Set variables"
file_count = 0
overall_size = 0
data = []
"Loop over files and extract the images"
if not os.path.exists('xl'):
for file in files:
with ZipFile(file) as working_zip:
image_list = [name for name in working_zip.namelist() if is_image(name)]
for img in image_list:
overall_size = overall_size + working_zip.getinfo(img).file_size
file_count = len(image_list)
working_zip.extractall("", image_list)
for img in image_list:
os.rename(img, f'xl/media/{file}.bin')
data.append(file_count)
data.append(overall_size)
"Create list of pasting locations for in excel"
cellcycletemp = ['A', 'H', 'O', 'V', 'AC']
rows = 4
cellcycle = [cellcycletemp[n%rows] + str(n//rows+1+12*(n//rows)+1) for n in range(120)]
"Create excel file and paste .bin images into it"
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
imagelist = [img for img in os.listdir('xl/media/.') if '.bin' in img]
for n, file in enumerate(imagelist):
img = openpyxl.drawing.image.Image('xl/media/' + file)
img.anchor = cellcycle[n]
ws.add_image(img)
wb.save('imgsave/combined images.xlsx')
这是我最终得到的错误:
Traceback (most recent call last):
File "C:\<path>\test_zipandpaste.py", line 67, in <module>
wb.save('imgsave/combined images.xlsx')
File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\workbook\workbook.py", line 407, in save
save_workbook(self, filename)
File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 293, in save_workbook
writer.save()
File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 275, in save
self.write_data()
File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 94, in write_data
self.manifest._write(archive, self.workbook)
File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\packaging\manifest.py", line 181, in _write
self._register_mimetypes(filenames=archive.namelist())
File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\packaging\manifest.py", line 193, in _register_mimetypes
mime = mimetypes.types_map[True][ext]
KeyError: '.wmf'
Process finished with exit code 1
编辑:在我最初发布的代码中发现了一个错误并修复了它。
1条答案
按热度按时间wmomyfyw1#
实际上,我找到了一种不用openpyxl也能做到这一点的方法。Python有一个内置的库xlsxwriter,它可以处理.wmf文件,也允许它粘贴.bin文件。