You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将子文件夹内的图片重命名为子文件夹名称?

批量重命名文件解决方案

Python 脚本(跨平台)

这个脚本可遍历指定根目录下的所有主文件夹,深入每个子文件夹后,将Img_one.GIF重命名为子文件夹名称去掉SubFolder前缀后的名称(保留原后缀)。

import os

# 替换为你的主文件夹所在根目录路径
root_dir = "./your_main_folders_root"

# 遍历根目录下的所有主文件夹
for main_folder in os.listdir(root_dir):
    main_folder_path = os.path.join(root_dir, main_folder)
    if not os.path.isdir(main_folder_path):
        continue
    
    # 遍历主文件夹下的所有子文件夹
    for sub_folder in os.listdir(main_folder_path):
        sub_folder_path = os.path.join(main_folder_path, sub_folder)
        if not os.path.isdir(sub_folder_path):
            continue
        
        old_img_path = os.path.join(sub_folder_path, "Img_one.GIF")
        if os.path.exists(old_img_path):
            # 生成新文件名:去掉"SubFolder"前缀,保留原后缀
            new_filename = sub_folder.replace("SubFolder", "") + ".GIF"
            new_img_path = os.path.join(sub_folder_path, new_filename)
            
            os.rename(old_img_path, new_img_path)
            print(f"已重命名: {old_img_path} → {new_img_path}")

使用提示

  • 将root_dir替换为实际的主文件夹根目录(如C:/Users/xxx/MainFolders或/home/xxx/main_folders)
  • 操作前建议备份文件,避免意外
  • 若无需去掉SubFolder前缀,直接修改为new_filename = sub_folder + ".GIF"即可

Windows 批处理脚本

适用于Windows系统:

@echo off
setlocal enabledelayedexpansion

:: 替换为你的主文件夹所在根目录
set "root_dir=C:\your_main_folders_root"

:: 遍历主文件夹
for /d %%M in ("%root_dir%\*") do (
    :: 遍历主文件夹下的子文件夹
    for /d %%S in ("%%M\*") do (
        set "sub_folder_name=%%~nS"
        set "new_name=!sub_folder_name:SubFolder=!"
        if exist "%%S\Img_one.GIF" (
            ren "%%S\Img_one.GIF" "!new_name!.GIF"
            echo 已重命名: %%S\Img_one.GIF → %%S\!new_name!.GIF
        )
    )
)

pause

Linux/macOS Shell 脚本

适用于Linux或macOS系统:

#!/bin/bash

# 替换为你的主文件夹所在根目录
root_dir="/your_main_folders_root"

# 遍历所有主文件夹下的直接子文件夹
find "$root_dir" -type d -mindepth 2 -maxdepth 2 | while read sub_folder; do
    old_img="$sub_folder/Img_one.GIF"
    if [ -f "$old_img" ]; then
        sub_folder_name=$(basename "$sub_folder")
        new_name="${sub_folder_name//SubFolder/}.GIF"
        mv "$old_img" "$sub_folder/$new_name"
        echo "已重命名: $old_img → $sub_folder/$new_name"
    fi
done

说明

  • -mindepth 2 -maxdepth 2确保只处理主文件夹下的直接子文件夹
  • 若无需去掉SubFolder前缀,修改为new_name="$sub_folder_name.GIF"即可

内容的提问来源于stack exchange,提问作者Lauren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 20:47:19