import os
import re

index = 0

def get_files_in_directory(path):
    files = []
    for root, dirs, filenames in os.walk(path):
        for filename in filenames:
            files.append(os.path.join(root, filename))
    return files


def rename_files(path, dir_name, file_pattern):
    # 获取目录下所有文件
    files = get_files_in_directory(path)

    # 创建目标目录
    output_dir = os.path.join(path, dir_name)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 遍历文件
    for file in files:
        # 匹配文件名
        if file_pattern in file:
            global index
            index += 1
            file_extension = os.path.splitext(file)[1]
            new_file = file_pattern + "_" + str(index) + file_extension
            # print(os.path.join(path, file), "to", os.path.join(output_dir, new_file), "\n")
            # continue
            os.rename(os.path.join(path, file), os.path.join(output_dir, new_file))


# 示例：遍历目录及其子目录中的所有相同名称的文件，并将它们放入一个目录下，按照数字从小到大的顺序重命名
path = "/home/zx/Tof_3D/saveImage"
dir_name = "/home/zx/Tof_3D/AllImage"
file_pattern = "Depth"
rename_files(path, dir_name, file_pattern)
