You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本实现图像与JSON文件复制、重命名及分类排序

脚本完善方案

针对文件分类整理需求,我对原有脚本做了逻辑修复和汉化,完全符合命名规则、目录结构要求,所有交互提示均改为中文,修复了原脚本的已知bug。


主要修复调整点

  • 修复原脚本编号范围生成漏值问题:比如输入561-568现在会正确包含首尾编号,生成561到568的完整序列
  • 修正原脚本状态映射写反、单词拼写错误:输入0(OK)对应normal目录,输入1(NG)对应anomaly目录,自定义状态直接按输入值生成目录名
  • 严格匹配目录规则:仅编号为2的子目录会创建color_images文件夹,且只存放文件名含0000000005标识的彩色图像;编号3、4的子目录仅生成grey_images和json文件夹,不会创建彩色图目录,也不会存入彩色图
  • 保留彩色图重命名逻辑:复制到color_images的文件会自动删除文件名中的_color字段,符合命名要求
  • 增加输入异常捕获:输入格式错误时会提示重新输入,不会直接崩溃退出
  • 优化路径兼容性:Windows、Linux/macOS系统均可正常运行,复制文件时保留原始创建时间、修改时间等元信息

完善后完整代码

import os
import shutil
from datetime import date

def gen_range(text):
    start, end = [int(i.strip()) for i in text.split("-")]
    return list(range(start, end + 1))

def get_user_input():
    nums = input("请输入产品编号,支持三种格式,示例:123;135;561-568;12\n").strip()
    values = []
    if ";" in nums:
        for value in [i.strip() for i in nums.split(';') if i.strip()]:
            if "-" in value:
                values += gen_range(value)
            else:
                if not value.isdigit():
                    raise ValueError("编号只能为数字")
                values.append(int(value))
    elif nums.isdigit():
        values = [int(nums)]
    elif "-" in nums:
        values = gen_range(nums)
    else:
        raise ValueError("输入格式不符合要求")
    return list(map(str, values))

def get_input_values():
    while True:
        try:
            nums = get_user_input()
            product = input("请输入产品名称:").strip()
            status = input("请输入产品状态:\n输入0代表OK\n输入1代表NG\n输入其他内容代表自定义状态\n").strip()
            if status == "0":
                status_show = "normal"
            elif status == "1":
                status_show = "anomaly"
            else:
                status_show = status
            print("\n当前输入参数:")
            print(f"产品编号列表:{nums}")
            print(f"产品名称:{product}")
            print(f"产品状态:{status_show}")
            correct = input("确认信息无误请输入yes,输入其他内容重新填写:").strip().lower()
            if correct == "yes":
                return {"numbers": nums, "status": status_show, "product": product}
        except Exception as e:
            print(f"输入错误:{str(e)},请重新输入\n")

def output_path(filename, status, product, outpaths):
    today = "".join(str(date.today()).split("-"))
    parts = filename.split("_")
    # 匹配子目录编号规则
    if len(parts) >= 2 and parts[1] in outpaths:
        num = outpaths[parts[1]]
    else:
        num = "3"
        if len(parts) >= 2:
            outpaths[parts[1]] = num
    subdir = "_".join([today, product, str(num), status])
    file_ext = os.path.splitext(filename)[1].lower()
    is_color_img = "_color_" in filename

    if file_ext == ".json":
        path = os.path.join(today, subdir, "json")
    elif is_color_img:
        # 非编号2目录、非0000000005标识的彩色图直接跳过,不存储
        if num != "2" or parts[1] != "0000000005":
            return None, None
        path = os.path.join(today, subdir, "color_images")
    else:
        path = os.path.join(today, subdir, "grey_images")
    
    if not os.path.exists(path):
        os.makedirs(path)
    # 彩色图重命名,删除_color字段
    final_filename = filename.replace("_color", "") if is_color_img else filename
    return path, final_filename

def copyfiles(numbers=None, status=None, product=None):
    found_nums = set()
    outpaths = {"0000000005": "2", "0000000011": "4"}
    # 遍历当前目录及所有子目录
    for root, _, files in os.walk('./'):
        for filename in files:
            file_parts = filename.split('_')
            if not file_parts:
                continue
            part = file_parts[0]
            name, ext = os.path.splitext(filename)
            if part in numbers and ext.lower() in [".json", ".jpeg", ".jpg"]:
                found_nums.add(part)
                origin_path = os.path.join(root, filename)
                target_dir, final_name = output_path(filename, status, product, outpaths)
                if not target_dir:
                    continue
                dest_path = os.path.join(target_dir, final_name)
                try:
                    shutil.copy2(origin_path, dest_path)
                    print(f"[成功] 已复制:{filename}")
                except Exception as e:
                    print(f"[失败] {filename} 复制出错,原因:{str(e)}")
    # 输出未找到的编号
    for number in numbers:
        if number not in found_nums:
            print(f"[提示] 未找到编号为 {number} 的对应文件")

if __name__ == "__main__":
    params = get_input_values()
    copyfiles(**params)

使用方法

  1. 将脚本放到待整理文件的根目录下运行
  2. 按提示输入产品编号,支持单编号、分号分隔多编号、横杠分隔编号范围三种格式
  3. 依次输入产品名称、产品状态,确认参数无误后输入yes启动复制
  4. 脚本会自动遍历当前目录所有子文件夹,匹配符合要求的.jpg/.jpeg/.json文件,按规则生成日期命名的根目录、分类子目录,自动完成重命名和复制
  5. 执行过程中实时输出复制结果,执行完成后会提示未找到对应文件的编号

内容的提问来源于stack exchange,提问作者user17920776

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 07:06:23