如何使用Python批量重命名文件夹内文件并移除下划线字符
Python批量移除文件名中的下划线实现方法
以下是直接可用的Python代码,实现批量移除指定文件夹内文件名中的下划线:
import os # 替换为你的目标文件夹路径,Windows路径可加r前缀避免转义 target_directory = r"你的文件夹路径" # 遍历目标文件夹中的所有条目 for item in os.listdir(target_directory): item_path = os.path.join(target_directory, item) # 只处理文件,跳过子文件夹 if not os.path.isfile(item_path): continue # 分离文件名主体和扩展名,仅移除主体中的下划线 file_name, file_ext = os.path.splitext(item) new_file_name = file_name.replace("_", "") + file_ext # 构造新旧文件路径并执行重命名 old_path = item_path new_path = os.path.join(target_directory, new_file_name) os.rename(old_path, new_path)
注意事项:
- 执行前务必备份目标文件夹内的文件,避免意外操作导致文件丢失
- 如果需要连扩展名中的下划线也一并移除,可修改文件名处理逻辑,直接对整个文件名做替换:
new_file_name = item.replace("_", "") - Windows系统路径建议使用原始字符串(如
r"C:\Test\Files"),防止转义字符引发错误
内容的提问来源于stack exchange,提问作者Vectorst
相关产品推荐
相关产品推荐

