| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 图片文件重命名脚本
- 将 d:\data\123456\reorganized_frames 文件夹中的图片文件序号从881开始重新编号
- 原文件: frame_000000.jpg -> frame_000880.jpg
- 新文件: frame_000881.jpg -> frame_001761.jpg
- """
- import os
- import re
- import shutil
- from pathlib import Path
- def rename_frames(source_dir, start_number=881, dry_run=True):
- """
- 重命名帧文件,将序号从指定数字开始
-
- Args:
- source_dir (str): 源文件夹路径
- start_number (int): 起始序号,默认881
- dry_run (bool): 是否为测试模式,True时只显示操作不实际执行
-
- Returns:
- tuple: (成功数量, 失败数量, 错误列表)
- """
- source_path = Path(source_dir)
-
- if not source_path.exists():
- print(f"错误: 源文件夹不存在: {source_dir}")
- return 0, 0, [f"源文件夹不存在: {source_dir}"]
-
- # 获取所有符合格式的图片文件
- frame_pattern = re.compile(r'^frame_(\d{6})\.jpg$')
- files_to_rename = []
-
- for file_path in source_path.iterdir():
- if file_path.is_file():
- match = frame_pattern.match(file_path.name)
- if match:
- original_number = int(match.group(1))
- files_to_rename.append((file_path, original_number))
-
- # 按原始序号排序
- files_to_rename.sort(key=lambda x: x[1])
-
- print(f"找到 {len(files_to_rename)} 个符合格式的图片文件")
- print(f"序号范围: {files_to_rename[0][1]} - {files_to_rename[-1][1]}")
- print(f"新序号将从 {start_number} 开始")
- print(f"模式: {'测试模式 (不实际执行)' if dry_run else '实际执行模式'}")
- print("-" * 50)
-
- success_count = 0
- error_count = 0
- errors = []
-
- # 为了避免文件名冲突,我们需要使用临时文件名
- # 先重命名为临时文件名,然后再重命名为最终文件名
- temp_files = []
-
- try:
- # 第一步:重命名为临时文件名
- for i, (file_path, original_number) in enumerate(files_to_rename):
- temp_name = f"temp_{i:06d}.jpg"
- temp_path = file_path.parent / temp_name
-
- if dry_run:
- print(f"[测试] {file_path.name} -> {temp_name}")
- else:
- try:
- file_path.rename(temp_path)
- temp_files.append((temp_path, i))
- print(f"临时重命名: {file_path.name} -> {temp_name}")
- except Exception as e:
- error_msg = f"临时重命名失败: {file_path.name} -> {temp_name}, 错误: {str(e)}"
- print(error_msg)
- errors.append(error_msg)
- error_count += 1
-
- # 第二步:从临时文件名重命名为最终文件名
- for temp_path, index in temp_files:
- new_number = start_number + index
- new_name = f"frame_{new_number:06d}.jpg"
- final_path = temp_path.parent / new_name
-
- if dry_run:
- print(f"[测试] temp_{index:06d}.jpg -> {new_name}")
- else:
- try:
- temp_path.rename(final_path)
- print(f"最终重命名: {temp_path.name} -> {new_name}")
- success_count += 1
- except Exception as e:
- error_msg = f"最终重命名失败: {temp_path.name} -> {new_name}, 错误: {str(e)}"
- print(error_msg)
- errors.append(error_msg)
- error_count += 1
-
- # 如果是测试模式,计算成功数量
- if dry_run:
- success_count = len(files_to_rename)
-
- except Exception as e:
- error_msg = f"重命名过程中发生未预期错误: {str(e)}"
- print(error_msg)
- errors.append(error_msg)
- error_count += 1
-
- print("-" * 50)
- print(f"操作完成!")
- print(f"成功: {success_count} 个文件")
- print(f"失败: {error_count} 个文件")
-
- if errors:
- print("\n错误详情:")
- for error in errors:
- print(f" - {error}")
-
- return success_count, error_count, errors
- def main():
- """主函数"""
- # 配置参数
- source_directory = r"d:\data\123456\reorganized_frames"
- start_number = 881
-
- print("=" * 60)
- print("图片文件重命名工具")
- print("=" * 60)
- print(f"源文件夹: {source_directory}")
- print(f"起始序号: {start_number}")
- print()
-
- # 首先进行测试运行
- print("🔍 执行测试运行...")
- success, errors, error_list = rename_frames(source_directory, start_number, dry_run=True)
-
- if errors > 0:
- print(f"\n❌ 测试运行发现 {errors} 个错误,请检查后再执行实际操作")
- return
-
- print(f"\n✅ 测试运行成功,将处理 {success} 个文件")
-
- # 询问用户是否继续
- while True:
- user_input = input("\n是否执行实际重命名操作? (y/n): ").strip().lower()
- if user_input in ['y', 'yes', '是']:
- break
- elif user_input in ['n', 'no', '否']:
- print("操作已取消")
- return
- else:
- print("请输入 y 或 n")
-
- # 执行实际重命名
- print("\n🚀 执行实际重命名操作...")
- success, errors, error_list = rename_frames(source_directory, start_number, dry_run=False)
-
- if errors == 0:
- print(f"\n🎉 重命名操作完全成功! 共处理 {success} 个文件")
- else:
- print(f"\n⚠️ 重命名操作完成,但有 {errors} 个错误")
- if __name__ == "__main__":
- main()
|