Share

文件名清洗

import os

def rename_files(directory_path):
    # 遍历目录中的文件
    for filename in os.listdir(directory_path):
        # 构建文件的完整路径
        file_path = os.path.join(directory_path, filename)

        # 检查是否是文件
        if os.path.isfile(file_path):
            # 找到日期部分的结束位置
            date_end_index = filename.find("_")
            
            # 如果找到了日期部分,进行重命名
            if date_end_index != -1:
                # 找到扩展名的起始位置
                extension_start_index = filename.rfind(".")
                
                # 构建新的文件名
                new_filename = filename[date_end_index+1:extension_start_index]
                new_filename = new_filename.replace("#", "")
                
                # 获取原扩展名
                extension = filename[extension_start_index:]
                
                new_file_path = os.path.join(directory_path, new_filename + extension)
                
                # 处理重名情况
                count = 1
                while os.path.exists(new_file_path):
                    new_filename = f"{new_filename[:-2]}_{count:02d}"
                    new_file_path = os.path.join(directory_path, new_filename + extension)
                    count += 1
                
                os.rename(file_path, new_file_path)
                print(f"重命名文件:{filename} -> {new_filename + extension}")

if __name__ == "__main__":
    directory_path = r"D:\furensiwen1"
    rename_files(directory_path)