图片命名顺序在一张excel的第一列
先爬取word中的所有图片
接着创建图片序列名称字段
遍历文件夹中的图片进行重命名
import docx
import os, re
import xlwt
import openpyxl
from openpyxl import Workbook, workbook
from openpyxl import load_workbook
import zipfile
import shutil
# 读取命名前缀到nameex
wb = load_workbook('图片顺序.xlsx')
ws = wb['Sheet1'] # sheet名称
sheet = wb.active
a = sheet.max_row
nameex = []
i = 0
while i < a:
i = i + 1
nameex.insert(i, ws.cell(i, 1).value)
nameend = ['001', '002', '003', '004']
doc_path = 'word_path/test.docx' #在这里更换你想要的路径
img_path = 'allpictures/' #在这里更换你想要的路径
os.makedirs(img_path, exist_ok=True)
doc = zipfile.ZipFile(doc_path)
img_list=[]
img_list_error=[]
for info in doc.infolist():
if info.filename.endswith((".png", ".jpeg", ".gif")):
doc.extract(info.filename, img_path)
img_list_error.append(info.filename)
print(img_list_error)
path1 = "allpictures/word/media"
filelist1 = os.listdir(path1)
total_num = len(filelist1)
for m in range(total_num+1):
image_name="image"+str(m)+".jpeg"
img_list.append(image_name)
print(img_list)
path = r"allpictures\word\media"
j = 0
k = 0
for item in img_list:
if item.endswith('.jpeg'):
project_name = nameex[j]
fid = nameend[k]
img_name = f'{project_name}_{fid}.jpeg'
src = os.path.join(os.path.abspath(path), item)
dst = os.path.join(os.path.abspath(path), img_name)
try:
os.rename(src, dst)
k = k + 1
if (k > 3):
k = 0
j = j + 1
except:
print(project_name)