Python遍历所有文件夹并执行函数:批量修改含_L2的文件名
解决遍历所有文件夹并重命名文件的问题
Hey there! Let's fix this up for you. The main issue with your current code is that you're not actually using the directories from os.walk to process subfolders—right now you're just running deleteInCurrent() on your starting directory over and over. Here's how to adjust it properly:
第一步:修改函数,让它接收目标路径
首先,把你的函数改成接受一个目录路径参数,这样它可以处理任意指定的文件夹,而不是固定当前工作目录:
import os def rename_files_in_dir(target_dir): # 获取目标目录下的所有文件和文件夹 items = os.listdir(target_dir) for item in items: # 拼接完整路径,避免处理子文件夹时找不到文件 full_path = os.path.join(target_dir, item) # 只处理文件,跳过文件夹(os.walk会帮我们遍历子文件夹) if os.path.isfile(full_path): # 拆分文件名和扩展名,用内置方法更可靠 name_part, ext_part = os.path.splitext(item) # 检查文件名是否包含目标标识 if '_L2' in name_part: # 生成新文件名:去掉末尾3个字符 + 原扩展名 new_name = f"{name_part[:-3]}{ext_part}" new_full_path = os.path.join(target_dir, new_name) # 安全重命名:避免覆盖已存在的文件 if not os.path.exists(new_full_path): os.rename(full_path, new_full_path) print(f"Renamed: {item} -> {new_name}") else: print(f"Skipped {item}: {new_name} already exists")
第二步:用os.walk遍历所有文件夹
现在使用os.walk遍历起始目录下的所有子目录,对每个目录调用上面的函数:
root_dir = os.getcwd() print(f"Starting from directory: {root_dir}") # os.walk会返回当前遍历的目录、子目录列表、文件列表,我们只需要当前目录 for root, _, _ in os.walk(root_dir): rename_files_in_dir(root)
关键改进点说明
- 使用完整路径:用
os.path.join拼接路径,避免在子文件夹中处理时出现文件找不到的问题。 - 区分文件与文件夹:用
os.path.isfile确保只处理文件,跳过文件夹(os.walk会自动遍历所有子文件夹)。 - 简化文件名操作:用
os.path.splitext替代手动rsplit,代码更简洁且兼容各种扩展名格式。 - 安全检查:重命名前确认新文件不存在,避免意外覆盖已有文件。
这样运行代码后,就会遍历你当前工作目录下的所有文件夹(包括嵌套的子文件夹),自动重命名所有符合条件的文件啦!
内容的提问来源于stack exchange,提问作者JunKim
相关产品推荐
相关产品推荐

