rename.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 图片文件重命名脚本
  5. 将 d:\data\123456\reorganized_frames 文件夹中的图片文件序号从881开始重新编号
  6. 原文件: frame_000000.jpg -> frame_000880.jpg
  7. 新文件: frame_000881.jpg -> frame_001761.jpg
  8. """
  9. import os
  10. import re
  11. import shutil
  12. from pathlib import Path
  13. def rename_frames(source_dir, start_number=881, dry_run=True):
  14. """
  15. 重命名帧文件,将序号从指定数字开始
  16. Args:
  17. source_dir (str): 源文件夹路径
  18. start_number (int): 起始序号,默认881
  19. dry_run (bool): 是否为测试模式,True时只显示操作不实际执行
  20. Returns:
  21. tuple: (成功数量, 失败数量, 错误列表)
  22. """
  23. source_path = Path(source_dir)
  24. if not source_path.exists():
  25. print(f"错误: 源文件夹不存在: {source_dir}")
  26. return 0, 0, [f"源文件夹不存在: {source_dir}"]
  27. # 获取所有符合格式的图片文件
  28. frame_pattern = re.compile(r'^frame_(\d{6})\.jpg$')
  29. files_to_rename = []
  30. for file_path in source_path.iterdir():
  31. if file_path.is_file():
  32. match = frame_pattern.match(file_path.name)
  33. if match:
  34. original_number = int(match.group(1))
  35. files_to_rename.append((file_path, original_number))
  36. # 按原始序号排序
  37. files_to_rename.sort(key=lambda x: x[1])
  38. print(f"找到 {len(files_to_rename)} 个符合格式的图片文件")
  39. print(f"序号范围: {files_to_rename[0][1]} - {files_to_rename[-1][1]}")
  40. print(f"新序号将从 {start_number} 开始")
  41. print(f"模式: {'测试模式 (不实际执行)' if dry_run else '实际执行模式'}")
  42. print("-" * 50)
  43. success_count = 0
  44. error_count = 0
  45. errors = []
  46. # 为了避免文件名冲突,我们需要使用临时文件名
  47. # 先重命名为临时文件名,然后再重命名为最终文件名
  48. temp_files = []
  49. try:
  50. # 第一步:重命名为临时文件名
  51. for i, (file_path, original_number) in enumerate(files_to_rename):
  52. temp_name = f"temp_{i:06d}.jpg"
  53. temp_path = file_path.parent / temp_name
  54. if dry_run:
  55. print(f"[测试] {file_path.name} -> {temp_name}")
  56. else:
  57. try:
  58. file_path.rename(temp_path)
  59. temp_files.append((temp_path, i))
  60. print(f"临时重命名: {file_path.name} -> {temp_name}")
  61. except Exception as e:
  62. error_msg = f"临时重命名失败: {file_path.name} -> {temp_name}, 错误: {str(e)}"
  63. print(error_msg)
  64. errors.append(error_msg)
  65. error_count += 1
  66. # 第二步:从临时文件名重命名为最终文件名
  67. for temp_path, index in temp_files:
  68. new_number = start_number + index
  69. new_name = f"frame_{new_number:06d}.jpg"
  70. final_path = temp_path.parent / new_name
  71. if dry_run:
  72. print(f"[测试] temp_{index:06d}.jpg -> {new_name}")
  73. else:
  74. try:
  75. temp_path.rename(final_path)
  76. print(f"最终重命名: {temp_path.name} -> {new_name}")
  77. success_count += 1
  78. except Exception as e:
  79. error_msg = f"最终重命名失败: {temp_path.name} -> {new_name}, 错误: {str(e)}"
  80. print(error_msg)
  81. errors.append(error_msg)
  82. error_count += 1
  83. # 如果是测试模式,计算成功数量
  84. if dry_run:
  85. success_count = len(files_to_rename)
  86. except Exception as e:
  87. error_msg = f"重命名过程中发生未预期错误: {str(e)}"
  88. print(error_msg)
  89. errors.append(error_msg)
  90. error_count += 1
  91. print("-" * 50)
  92. print(f"操作完成!")
  93. print(f"成功: {success_count} 个文件")
  94. print(f"失败: {error_count} 个文件")
  95. if errors:
  96. print("\n错误详情:")
  97. for error in errors:
  98. print(f" - {error}")
  99. return success_count, error_count, errors
  100. def main():
  101. """主函数"""
  102. # 配置参数
  103. source_directory = r"d:\data\123456\reorganized_frames"
  104. start_number = 881
  105. print("=" * 60)
  106. print("图片文件重命名工具")
  107. print("=" * 60)
  108. print(f"源文件夹: {source_directory}")
  109. print(f"起始序号: {start_number}")
  110. print()
  111. # 首先进行测试运行
  112. print("🔍 执行测试运行...")
  113. success, errors, error_list = rename_frames(source_directory, start_number, dry_run=True)
  114. if errors > 0:
  115. print(f"\n❌ 测试运行发现 {errors} 个错误,请检查后再执行实际操作")
  116. return
  117. print(f"\n✅ 测试运行成功,将处理 {success} 个文件")
  118. # 询问用户是否继续
  119. while True:
  120. user_input = input("\n是否执行实际重命名操作? (y/n): ").strip().lower()
  121. if user_input in ['y', 'yes', '是']:
  122. break
  123. elif user_input in ['n', 'no', '否']:
  124. print("操作已取消")
  125. return
  126. else:
  127. print("请输入 y 或 n")
  128. # 执行实际重命名
  129. print("\n🚀 执行实际重命名操作...")
  130. success, errors, error_list = rename_frames(source_directory, start_number, dry_run=False)
  131. if errors == 0:
  132. print(f"\n🎉 重命名操作完全成功! 共处理 {success} 个文件")
  133. else:
  134. print(f"\n⚠️ 重命名操作完成,但有 {errors} 个错误")
  135. if __name__ == "__main__":
  136. main()