rename.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import os
  2. import re
  3. index = 0
  4. def get_files_in_directory(path):
  5. files = []
  6. for root, dirs, filenames in os.walk(path):
  7. for filename in filenames:
  8. files.append(os.path.join(root, filename))
  9. return files
  10. def rename_files(path, dir_name, file_pattern):
  11. # 获取目录下所有文件
  12. files = get_files_in_directory(path)
  13. # 创建目标目录
  14. output_dir = os.path.join(path, dir_name)
  15. if not os.path.exists(output_dir):
  16. os.makedirs(output_dir)
  17. # 遍历文件
  18. for file in files:
  19. # 匹配文件名
  20. if file_pattern in file:
  21. global index
  22. index += 1
  23. file_extension = os.path.splitext(file)[1]
  24. new_file = file_pattern + "_" + str(index) + file_extension
  25. # print(os.path.join(path, file), "to", os.path.join(output_dir, new_file), "\n")
  26. # continue
  27. os.rename(os.path.join(path, file), os.path.join(output_dir, new_file))
  28. # 示例:遍历目录及其子目录中的所有相同名称的文件,并将它们放入一个目录下,按照数字从小到大的顺序重命名
  29. path = "/home/zx/Tof_3D/saveImage"
  30. dir_name = "/home/zx/Tof_3D/AllImage"
  31. file_pattern = "Depth"
  32. rename_files(path, dir_name, file_pattern)