照片与Excel表比对Python脚本报错修复及功能完善请求
错误原因分析
报错AttributeError: 'NoneType' object has no attribute 'split'是因为你的Excel表C列(物品名称列)存在空白单元格,遍历这些单元格时,row[0]的值为None,而None对象没有split方法,直接调用就会触发这个错误。
修正后的完整脚本
import os import openpyxl from openpyxl.styles import PatternFill # 替换为实际路径 photo_dir = "你的照片目录路径" excel_dir = "你的原Excel文件路径" new_excel_dir = "生成的新Excel文件路径" # 加载原Excel表 wb_table = openpyxl.load_workbook(excel_dir) sheet_table = wb_table.active # 创建新Excel表并设置表头 wb_new_table = openpyxl.Workbook() sheet_new_table = wb_new_table.active sheet_new_table.append(["物品ID", "图片1", "图片2", "图片3", "图片4"]) # 整理照片:按物品ID分组,记录存在的后缀 photo_groups = {} for filename in os.listdir(photo_dir): file_path = os.path.join(photo_dir, filename) if not os.path.isfile(file_path) or not filename.endswith(".jpg"): continue name_without_ext = filename.split(".")[0] # 拆分物品ID和后缀 if "-" in name_without_ext: item_id, suffix = name_without_ext.rsplit("-", 1) if suffix.isdigit() and 1 <= int(suffix) <= 4: photo_groups.setdefault(item_id, set()).add(f"-{suffix}") else: item_id = name_without_ext photo_groups.setdefault(item_id, set()).add("") # 无后缀对应图片1 # 设置红色填充样式 red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid") # 遍历原Excel表的物品ID行(从第2行开始,跳过表头) for row in sheet_table.iter_rows(min_row=2, values_only=True): item_id = row[2] # C列对应索引2(从0开始计数) # 跳过空白的物品ID行 if not item_id: continue item_id_str = str(item_id).split(".")[0] # 获取该物品已存在照片的后缀集合 existing_suffixes = photo_groups.get(item_id_str, set()) # 构建新表行数据,标记图片存在/缺失状态 new_row = [item_id_str] # 图片1对应无后缀,图片2对应-1,图片3对应-2,图片4对应-3 for img_idx in range(1, 5): suffix = "" if img_idx == 1 else f"-{img_idx-1}" new_row.append("存在" if suffix in existing_suffixes else "缺失") # 写入新表并标记缺失单元格 sheet_new_table.append(new_row) current_row = sheet_new_table.max_row for col_idx in range(2, 6): if new_row[col_idx-1] == "缺失": sheet_new_table.cell(row=current_row, column=col_idx).fill = red_fill # 保存新表 wb_new_table.save(new_excel_dir)
关键修正点说明
- 处理空白单元格:遍历Excel行时先判断物品ID是否为空,为空则直接跳过,避免调用
split方法报错。 - 照片分组整理:将同一物品的所有照片后缀收集到集合中,快速判断某张图片是否存在。
- 修正填充颜色:原脚本误用绿色(
00FF00),改为需求要求的红色(FF0000)。 - 完整实现需求:覆盖所有逻辑:检查4张图片的存在状态、写入缺失项、给缺失单元格添加红色背景。
内容的提问来源于stack exchange,提问作者Web Admin
相关产品推荐
相关产品推荐

