import os import re def clean_filename(filename): # 保留括号内的数字 filename = re.sub(r'(?<!\()\d+(?!\))', '', filename) # 将特殊符号(包括下划线)转换为空格,但保留括号、逗号和句点 filename = re.sub(r'[^\w\s\(\),\.]|_', ' ', filename) return filename def is_image_file(filename): for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff']: if filename.lower().endswith(ext): return True return False def rename_files_in_directory(directory): for root, dirs, files in os.walk(directory): for file in files: if is_image_file(file): new_name = clean_filename(file) old_file_path = os.path.join(root, file) new_file_path = os.path.join(root, new_name) os.rename(old_file_path, new_file_path) print(f'已重命名: {file} -> {new_name}') def main(): directory = input("请输入要处理的文件夹路径: ") rename_files_in_directory(directory) print("处理完成。") if __name__ == "__main__": main()
标签:__,特殊符号,filename,没用,directory,main,打标 From: https://www.cnblogs.com/zly324/p/17856229.html