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

使用os.walk重命名图片:提取文件夹名前缀作为图片名前缀

Fixing Your Image Renaming Script

Hey there! Let's work through the issues in your code and get it working exactly how you want it.

Key Problems in Your Current Code

  • You're trying to split files (which is a list of filenames) instead of the actual folder name. That's why you can't pull the correct prefix—you're targeting the wrong variable entirely!
  • You're using the top-level path to build file paths instead of root, which will break if you have subfolders (since images live in root, not the main folder you started with).
  • The counter i doesn't reset per folder, so images across different folders will have continuous numbering (probably not what you want unless you intend global numbering).

Corrected Code

import os

path = r'C:\folderPath'

for root, dirs, files in os.walk(path):
    # Grab the name of the current folder we're processing
    folder_name = os.path.basename(root)
    # Split the folder name ONLY at the first ' - ' to get our prefix
    prefix = folder_name.split(' - ', 1)[0]
    # Reset counter for each new folder (remove this line if you want global numbering)
    i = 1
    for image in files:
        # Optional: Only process image files to avoid renaming non-image items
        if image.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
            # Build the correct old and new file paths
            old_file_path = os.path.join(root, image)
            new_file_path = os.path.join(root, f"{prefix}_{i}.jpg")
            # Rename the file
            os.rename(old_file_path, new_file_path)
            i += 1

What's Changed & Why?

  1. Extract the Folder Name: os.path.basename(root) pulls just the folder name from the full directory path (e.g., "ABCDEF - THIS IS - MY FOLDER - NAME" from the full root path).
  2. Clean Split: folder_name.split(' - ', 1)[0] splits the folder name only once at the first occurrence of ' - ', so we reliably get the leftmost segment ("ABCDEF" in your example). The 1 ensures we don't split on any subsequent dashes in the folder name.
  3. Correct File Paths: Using root instead of the top-level path ensures we target the right files, even in nested subfolders.
  4. Image Filter: The optional check ensures we only rename image files, so you won't accidentally mess with documents or other non-image items.
  5. Per-Folder Numbering: Resetting i to 1 for each folder means each folder's images start counting from 1. If you want a single counter across all folders, move i = 1 outside the os.walk loop.

Example Output

For a folder named "ABCDEF - THIS IS - MY FOLDER - NAME" with images dsc_001.jpg and dsc_002.jpg, they'll be renamed to ABCDEF_1.jpg and ABCDEF_2.jpg respectively.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:10:15