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

使用Python按章节封面归类TIFF图片至对应目录

Python实现TIFF图片按章节封面归类

实现思路

  • 按文件名排序确保文件顺序与原编号一致(001、002...)
  • 通过自定义规则识别你手动修改后的封面文件
  • 识别到封面时创建对应目录,将封面及后续内容页移入,直到下一个封面出现

代码实现

import os
import shutil
from pathlib import Path

def is_cover(filename):
    # 自定义封面文件的判断规则,根据你手动修改的特征调整
    # 示例:如果封面文件名包含"cover"则判定为封面,可改为你的实际标记
    return "cover" in filename.lower()

def organize_tiff_files(source_dir):
    # 获取目录下所有TIFF格式文件
    tiff_files = [
        f for f in os.listdir(source_dir) 
        if f.lower().endswith('.tif') or f.lower().endswith('.tiff')
    ]
    # 按文件名排序,保证和原编号顺序一致
    tiff_files.sort()

    current_chapter_dir = None
    current_chapter_files = []

    for file in tiff_files:
        if is_cover(file):
            # 处理上一个章节的文件(如果存在)
            if current_chapter_dir and current_chapter_files:
                chapter_path = os.path.join(source_dir, current_chapter_dir)
                Path(chapter_path).mkdir(exist_ok=True)
                # 移动文件到对应目录
                for f in current_chapter_files:
                    src = os.path.join(source_dir, f)
                    dst = os.path.join(chapter_path, f)
                    shutil.move(src, dst)
            # 初始化当前章节:用封面文件名(去掉后缀)作为目录名
            current_chapter_dir = os.path.splitext(file)[0]
            current_chapter_files = [file]
        else:
            # 非封面文件加入当前章节列表
            if current_chapter_dir:
                current_chapter_files.append(file)
    
    # 处理最后一个章节的剩余文件
    if current_chapter_dir and current_chapter_files:
        chapter_path = os.path.join(source_dir, current_chapter_dir)
        Path(chapter_path).mkdir(exist_ok=True)
        for f in current_chapter_files:
            src = os.path.join(source_dir, f)
            dst = os.path.join(chapter_path, f)
            shutil.move(src, dst)

if __name__ == "__main__":
    # 替换为你的TIFF文件所在文件夹路径
    source_directory = "./your_tiff_folder"
    organize_tiff_files(source_directory)

使用说明

  • 修改is_cover函数的判断逻辑:比如你把封面命名为chapter1.tif而内容页是001.tif,可以改成判断文件名不以数字开头,或者包含你自定义的关键词
  • 替换source_directory为你的TIFF文件实际存放路径
  • 运行前建议先备份文件,避免误操作
  • 代码仅依赖Python内置模块,无需额外安装第三方库

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:20:33