Python操作目录最简方法及媒体中心文件批量整理方案咨询
Hey Sam, great job getting the parent folder renaming working—let’s knock out the rest of that media file organizer. I’ll break this down into actionable code and explain the simplest Python tools for directory operations, since that’s part of your question too.
First, Let’s Build the Subfile Organization Logic
Based on your pseudocode, here’s a practical implementation using Python’s modern pathlib module (we’ll talk about why this is the best choice for directory work in a bit). This script will:
- Scan a specified root directory for all folders
- Move/copy files from subfolders into their parent folder (handling name collisions to avoid overwrites)
- Sort files by size (largest first)
- Rename the largest file to match the parent folder’s name (adjust the naming rule as needed for your media center)
from pathlib import Path import shutil # Only needed if you want to copy instead of move def organize_media_folders(root_dir): root = Path(root_dir) # Iterate over every folder in the root directory for parent_folder in root.iterdir(): if not parent_folder.is_dir(): continue # Skip files in the root, only process folders # Step 1: Move/copy all files from subfolders to the parent folder # Use rglob('*') to catch files in nested subfolders too for file in parent_folder.rglob('*'): if file.is_file() and file.parent != parent_folder: # Handle duplicate filenames to avoid overwriting target_path = parent_folder / file.name counter = 1 while target_path.exists(): # Rename duplicates like "movie_1.mp4", "movie_2.mp4" stem = target_path.stem suffix = target_path.suffix target_path = parent_folder / f"{stem}_{counter}{suffix}" counter += 1 # Choose: move (rename) or copy (shutil.copy2 preserves metadata) file.rename(target_path) # This moves the file # shutil.copy2(file, target_path) # Uncomment this to copy instead # Step 2: Sort all files in the parent folder by size (largest first) all_files = [f for f in parent_folder.iterdir() if f.is_file()] # Skip hidden files if needed: add `and not f.name.startswith('.')` all_files.sort(key=lambda x: x.stat().st_size, reverse=True) # Step 3: Rename the largest file to match the parent folder if all_files: largest_file = all_files[0] # Example: parent folder is "Inception(2010)", rename to "Inception(2010).mp4" new_filename = f"{parent_folder.name}{largest_file.suffix}" new_path = parent_folder / new_filename # Again, handle duplicates just in case counter = 1 while new_path.exists(): new_path = parent_folder / f"{parent_folder.name}_{counter}{largest_file.suffix}" counter += 1 largest_file.rename(new_path) print(f"Renamed largest file in {parent_folder.name} to {new_path.name}") # Usage: Replace with your media directory path organize_media_folders("/path/to/your/media/root")
The Simplest Way to Handle Directories in Python: pathlib
Forget the old os.path module—pathlib is the modern, intuitive way to work with files and directories in Python 3.4+. Here’s why it’s better:
- Object-oriented syntax: Instead of messy
os.path.join("dir", "file"), just usePath("dir") / "file" - Built-in checks: Easily verify if a path is a folder (
path.is_dir()) or file (path.is_file()) - Clean metadata access: Get file size with
path.stat().st_size, creation time withpath.stat().st_ctime, etc. - Recursive scanning: Use
path.rglob('*')to find all files in nested subfolders (no need for nested loops)
Quick pathlib Cheat Sheet for Your Project:
- List all folders in a directory:
[p for p in Path("dir").iterdir() if p.is_dir()] - Get the size of a file:
Path("file.mp4").stat().st_size - Rename/move a file:
old_path.rename(new_path) - Copy a file (with metadata):
shutil.copy2(old_path, new_path)
Notes to Customize for Your Media Center
- If you only want to process immediate subfolders (not nested ones), replace
rglob('*')withiterdir()and add a check for subfolders first. - Adjust the renaming logic for the largest file—maybe you want to keep part of the original filename, or use a specific extension.
- Add error handling with
try-exceptblocks if you anticipate permission issues or broken files.
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

