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

Python批量重命名指定目录及子目录下的文件与文件夹求助

Hey there! Let’s work through this batch renaming issue together. You mentioned trying code that failed, so I’ll share a reliable cross-platform solution (plus fixes for common errors) and alternative approaches tailored to your directory structure.

Python Recursive Rename Solution

This script handles both files and folders, starting from the deepest subdirectories first (so we don’t break file paths by renaming parent folders early). It also includes error handling to tell you exactly what went wrong.

import os

def batch_rename(root_dir, rename_rule):
    # Traverse directories from deepest to shallowest to avoid path breaks
    for dirpath, dirnames, filenames in os.walk(root_dir, topdown=False):
        # Rename folders first
        for dirname in dirnames:
            old_full_path = os.path.join(dirpath, dirname)
            new_name = rename_rule(dirname)
            new_full_path = os.path.join(dirpath, new_name)
            try:
                os.rename(old_full_path, new_full_path)
                print(f"✅ Renamed folder: {old_full_path} → {new_full_path}")
            except Exception as e:
                print(f"❌ Failed to rename folder {old_full_path}: {str(e)}")
        
        # Rename files next
        for filename in filenames:
            old_full_path = os.path.join(dirpath, filename)
            new_name = rename_rule(filename)
            new_full_path = os.path.join(dirpath, new_name)
            try:
                os.rename(old_full_path, new_full_path)
                print(f"✅ Renamed file: {old_full_path} → {new_full_path}")
            except Exception as e:
                print(f"❌ Failed to rename file {old_full_path}: {str(e)}")

# Example rename rule: Customize this to fit your needs!
# This example replaces "file" with "document_" and "folder" with "dir_"
def custom_rename(name):
    if name.startswith("file"):
        return name.replace("file", "document_")
    elif name.startswith("folder"):
        return name.replace("folder", "dir_")
    else:
        return name  # Keep names that don't match the pattern

# Run the script: Replace with your actual top-level directory path
if __name__ == "__main__":
    target_directory = "/path/to/your/top-level-folder"
    batch_rename(target_directory, custom_rename)

Key Details to Avoid Errors

  • Topdown=False: This ensures we process subfolders first. If we renamed folder1 before its inner files, the path to folder1/file1 would break mid-execution.
  • Error Handling: The try/except blocks catch issues like:
    • Missing permissions (run as admin on Windows, use sudo on Linux/macOS if needed)
    • Files/folders being used by another program (close the app using them first)
    • Duplicate new names (adjust your custom_rename function to add suffixes like _1 if a name already exists)
  • Absolute Paths: Always use full paths for target_directory to avoid confusion with relative paths.
Alternative: Command-Line Approach (Linux/macOS)

If you prefer using terminal commands, use find with the -depth flag to handle subdirectories first:

# Rename all folders (add "renamed_" prefix)
find /path/to/top-level-folder -depth -type d -exec mv {} {}/../renamed_{} \;

# Rename all files (add "renamed_" prefix)
find /path/to/top-level-folder -depth -type f -exec mv {} {}/../renamed_{} \;

Customizing the Command

To match the same pattern as the Python script (replace "file" with "document_"), use:

# Rename files
find /path/to/top-level-folder -depth -type f -name "file*" -exec bash -c 'mv "$0" "${0/file/document_}"' {} \;

# Rename folders
find /path/to/top-level-folder -depth -type d -name "folder*" -exec bash -c 'mv "$0" "${0/folder/dir_}"' {} \;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:51:25