使用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
pathto build file paths instead ofroot, which will break if you have subfolders (since images live inroot, not the main folder you started with). - The counter
idoesn'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?
- 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 fullrootpath). - 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). The1ensures we don't split on any subsequent dashes in the folder name. - Correct File Paths: Using
rootinstead of the top-levelpathensures we target the right files, even in nested subfolders. - Image Filter: The optional check ensures we only rename image files, so you won't accidentally mess with documents or other non-image items.
- Per-Folder Numbering: Resetting
ito 1 for each folder means each folder's images start counting from 1. If you want a single counter across all folders, movei = 1outside theos.walkloop.
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
相关产品推荐
相关产品推荐

