批量重命名
import os import re import shutil def replace_double_underscore(folder_path): for root, dirs, files in os.walk(folder_path): for filename in files: if "__" in filename: new_filename = filename.replace("__", "_") os.rename(os.path.join(root, filename), os.path.join(root, new_filename)) def rename_with_incremental_suffix(folder_path): seen = {} for root, dirs, files in os.walk(folder_path): for filename in files: base, ext = os.path.splitext(filename) if base in seen: seen[base] += 1 new_filename = f"{base}({seen[base]}){ext}" else: seen[base] = 0 new_filename = filename os.rename(os.path.join(root, filename), os.path.join(root, new_filename)) def remove_prefix_before_first_underscore(folder_path): for root, dirs, files in os.walk(folder_path): for filename in files: base, ext = os.path.splitext(filename) base = re.sub(r'^[^_]*_', '', base) new_filename = f"{base}{ext}" os.rename(os.path.join(root, filename), os.path.join(root, new_filename)) def remove_digits_and_following_text(folder_path): for root, dirs, files in os.walk(folder_path): for filename in files: base, ext = os.path.splitext(filename) match = re.search(r'\d', base) if match: index = match.start() pos = base.rfind('_', 0, index) if pos != -1: base = base[:pos] new_filename = f"{base}{ext}" # Check if new filename already exists, if so, add incremental suffix i = 1 while os.path.exists(os.path.join(root, new_filename)): new_filename = f"{base}({i}){ext}" i += 1 os.rename(os.path.join(root, filename), os.path.join(root, new_filename)) def replace_underscores_with_spaces(folder_path): for root, dirs, files in os.walk(folder_path): for filename in files: new_filename = filename.replace("_", " ") os.rename(os.path.join(root, filename), os.path.join(root, new_filename)) def main(): folder_path = input("请输入文件夹地址:") # 第一步操作 replace_double_underscore(folder_path) print("第一步操作完成") # 第二步操作 rename_with_incremental_suffix(folder_path) print("第二步操作完成") # 第三步操作 remove_prefix_before_first_underscore(folder_path) rename_with_incremental_suffix(folder_path) print("第三步操作完成") # 第四步操作 remove_digits_and_following_text(folder_path) print("第四步操作完成") # 第五步操作 replace_underscores_with_spaces(folder_path) print("第五步操作完成") if __name__ == "__main__": main()
标签:root,filename,base,数据处理,path,新版,MJ,os,folder From: https://www.cnblogs.com/zly324/p/18182865