如何用Python移除影视子文件夹名称中的指定冗余内容(如720p、BluRay)
Hey there! Let's fix those cluttered movie/TV subfolder names once and for all. I've put together a complete, safe Python solution that handles all those annoying tags like 720p, BluRay, x264, and more. Here's how it works:
Core Approach
We'll build a script that:
- Targets all common redundant media tags (you can easily expand this list)
- Scans your target directory (and nested subfolders if needed)
- Cleans up folder names by removing tags, fixing messy separators, and avoiding naming conflicts
- Includes safety checks to prevent accidental overwrites
Full Code Implementation
import os import re def clean_media_folders(root_directory): # Define all redundant tags to remove (add/remove based on your needs) redundant_tags = [ r'720p', r'1080p', r'2160p', r'4K', r'8K', r'BluRay', r'WEB-DL', r'WEBRip', r'DVDrip', r'BDRip', r'HDR', r'HDR10', r'DV', r'DolbyVision', r'x264', r'x265', r'HEVC', r'AVC', r'AC3', r'DD5.1', r'DD7.1', r'Atmos', r'DTS', r'REMUX', r'Extended', r'Unrated', r'Director\'s Cut', r'YIFY', r'ETRG', r'RARBG' # Add common release groups here ] # Compile regex pattern: match tags regardless of case, with word boundaries tag_pattern = re.compile( r'\b(' + '|'.join(redundant_tags) + r')\b', re.IGNORECASE ) # Walk through all subfolders in the target directory for current_dir, subdirs, files in os.walk(root_directory): for folder_name in subdirs: original_name = folder_name # Step 1: Strip out all redundant tags cleaned_name = tag_pattern.sub('', original_name) # Step 2: Clean up messy separators (dots, hyphens, underscores → spaces) cleaned_name = re.sub(r'[\.\-_]+', ' ', cleaned_name) # Step 3: Remove extra spaces (leading, trailing, and consecutive) cleaned_name = re.sub(r'\s+', ' ', cleaned_name).strip() # Skip if the name is already clean if cleaned_name == original_name: continue # Build full paths for renaming original_path = os.path.join(current_dir, original_name) new_path = os.path.join(current_dir, cleaned_name) # Handle naming conflicts (add a counter if the new name already exists) counter = 1 while os.path.exists(new_path): new_path = os.path.join(current_dir, f"{cleaned_name} ({counter})") counter += 1 # Execute the rename (with error handling) try: os.rename(original_path, new_path) print(f"✅ Renamed: '{original_name}' → '{os.path.basename(new_path)}'") except Exception as e: print(f"❌ Failed to rename '{original_name}': {str(e)}") if __name__ == "__main__": # Replace this with your actual media folder path target_dir = "/path/to/your/media/library" # Windows users: use r"C:\Your\Media\Path" if os.path.isdir(target_dir): clean_media_folders(target_dir) print("\n✅ All clean!") else: print("❌ Error: Target directory doesn't exist!")
Key Details & Customization Tips
- Expand the Tag List: Add any other redundant terms you encounter (like specific release groups, language tags you don't need, etc.) to the
redundant_tagslist. - Case Insensitive: The regex matches tags regardless of capitalization (so
bluray,BLURAY, andBluRayall get removed). - Safety First: The script automatically adds a counter (e.g.,
Movie Name (1)) if the cleaned name already exists, so you never accidentally overwrite a folder. - Nested Folders: By default,
os.walkscans all nested subfolders. If you only want to clean top-level folders, replace theos.walkloop with a simpleos.listdircheck for directories.
Important Pre-Run Notes
- Backup First: Always make a copy of your media folders before running batch rename scripts—just in case!
- Test Small: Run the script on a small test folder first to verify it behaves exactly how you want.
- Permissions: Ensure you have read/write access to the target directory.
内容的提问来源于stack exchange,提问作者Enkráteia
相关产品推荐
相关产品推荐

