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.
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
folder1before its inner files, the path tofolder1/file1would break mid-execution. - Error Handling: The try/except blocks catch issues like:
- Missing permissions (run as admin on Windows, use
sudoon Linux/macOS if needed) - Files/folders being used by another program (close the app using them first)
- Duplicate new names (adjust your
custom_renamefunction to add suffixes like_1if a name already exists)
- Missing permissions (run as admin on Windows, use
- Absolute Paths: Always use full paths for
target_directoryto avoid confusion with relative paths.
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

