import os import uuid from pathlib import Path # 定义一个函数来生成唯一的文件名 def generate_unique_filename(extension): return f"{uuid.uuid4()}{extension}" # 定义支持的图片文件扩展名 supported_extensions = ['.jpg', '.jpeg', '.png', '.gif'] def rename_images_in_directory(directory): # 存储已生成的文件名以确保唯一性 generated_filenames = set() # 遍历目录 for root, dirs, files in os.walk(directory): for file in files: file_path = Path(root) / file extension = file_path.suffix.lower() if extension in supported_extensions: # 生成唯一文件名并保持扩展名不变 new_filename = generate_unique_filename(extension) while new_filename in generated_filenames: new_filename = generate_unique_filename(extension) generated_filenames.add(new_filename) # 生成新的文件路径 new_file_path = file_path.with_name(new_filename) # 重命名文件 os.rename(file_path, new_file_path) print(f"Renamed '{file_path}' to '{new_file_path}'") # 用户输入总目录 directory = input("请输入总目录的路径: ") rename_images_in_directory(directory)
标签:extension,filename,乱码,文件夹,file,path,directory,new,伪造 From: https://www.cnblogs.com/zly324/p/18006938