1. Problem Scenario: Cluttered Video File Name
In daily work and study, we often encounter file naming situations like this:
[1] Basic tutorial.mp4
[23] Advanced skills.mp4
[156] Project Practical .mp4
Although this naming method that contains numeric numbers is intuitive, there are two obvious problems:
- The number of digits is inconsistent, and the order will be incorrect when sorting
- The file name needs to be modified but the original file must be retained
This article will introduce how to use Python scriptsBatch copy and standardize namingVideo file, implement:
- Automatically fill 4-digit numbers
- Keep the original file without modifying it
- Intelligently identify valid files
- Complete copy file properties
2. Complete solution
import os import re import shutil def rename_and_copy_mp4_files(source_dir, target_dir): """Intelligently rename and copy video files Args: source_dir (str): Source directory path target_dir (str): Target directory path """ # Create a target directory (automatically handle existing situations) (target_dir, exist_ok=True) # traverse all files in the source directory for filename in (source_dir): # Use regular expressions to resolve file names pattern_match = (r'\[(\d+)\](.+)\.(mp4|avi|mov)$', filename, ) if pattern_match: # Extract filename component file_number = pattern_match.group(1) file_content = pattern_match.group(2).strip() file_ext = pattern_match.group(3).lower() # Format number (4 digits to make up for zeros) formatted_number = file_number.zfill(4) # Build a new file name new_filename = f"{formatted_number}_{file_content}.{file_ext}" # Build a full path src_path = (source_dir, filename) dst_path = (target_dir, new_filename) # Perform a copy operation with metadata shutil.copy2(src_path, dst_path) print(f"Successfully processed:{filename} → {new_filename}") else: print(f"Skip non-standard files:{filename}") if __name__ == "__main__": # Configure path (modify according to actual situation) SOURCE_DIR = r"E:\video_source" TARGET_DIR = r"E:\video_organized" rename_and_copy_mp4_files(SOURCE_DIR, TARGET_DIR)
3. Key technologies analysis
1. Intelligent path processing
(target_dir, exist_ok=True)
exist_ok=True
Parameters ensure:
- Automatically create when the target directory does not exist
- No error is reported when the directory already exists
- Automatically handle multi-level directory creation
2. Accurate file name matching
r'\[(\d+)\](.+)\.(mp4|avi|mov)$'
Regular expression decomposition:
- \[(\d+)\] Capture the numbers in square brackets
- (.+) Capture content of any length (at least 1 character)
- (mp4|avi|mov)$ supports multiple video formats
- Ignore case
Support matching formats:
- [123] Tutorial.mp4
- [45]
- [6] Test file.AVI
3. Digital formatting
file_number.zfill(4)
Conversion example:
- “1” → “0001”
- “23” → “0023”
- “156” → “0156”
4. Secure file copying
shutil.copy2(src, dst)
Differences from normal copying:
- Keep original creation time
- Keep the last modification time
- Keep file permission settings
- Keep other metadata
4. Usage Guide
Preparation steps
- Install Python 3.6+ environment
- Create script file
video_organizer.py
- Prepare the test directory (it is recommended to conduct tests first)
Configuration example
# Windows system exampleSOURCE_DIR = r"E:\training_videos" TARGET_DIR = r"D:\sorted_videos" # macOS/Linux example# SOURCE_DIR = "/Users/username/Videos/source" # TARGET_DIR = "/Volumes/external_drive/sorted_videos"
Execution effect
Original file | Generate files |
---|---|
[1] Introduction.mp4 | 0001_Introduction.mp4 |
[23] Basic lesson.avi | 0023_Basic Course.avi |
[156] Project Practical .mov | 0156_Project practical.mov |
V. Advanced extension suggestions
1. Add progress prompts
# Add before the loop startstotal_files = len([f for f in (source_dir) if (('.mp4', '.avi', '.mov'))]) processed = 0 # Add when processing is successfulprocessed += 1 print(f"schedule:{processed}/{total_files} ({processed/total_files:.1%})")
2. Protection against coverage mechanism
if (dst_path): base, ext = (new_filename) counter = 1 while (dst_path): new_filename = f"{base}_{counter}{ext}" dst_path = (target_dir, new_filename) counter += 1
3. Multithreaded acceleration
from import ThreadPoolExecutor def process_file(filename): # Original processing logic with ThreadPoolExecutor(max_workers=4) as executor: (process_file, (source_dir))
6. Things to note
Path format verification
• Use backslashes for Windows pathsr"E:\path"
• Other systems use forward slashes"/path/to/files"
Permissions issues
• Ensure read permissions to the source directory
• Ensure write permissions to the target directorySpecial character processing
• Automatically skip files containing illegal characters
• Add character filtering logic:
file_content = (r'[<>:"/\\|?*]', '', file_content)
Performance optimization
• It is recommended to add files above 10,000:
◦ Progress bar display
◦ Error logging
◦ Breakpoint continuous transmission function
7. Summary
Through this Python script, we implement:
- Batch processing of video files
- Intelligent specification numbering format
- Safely retain original files
- Quick deployment and use
Extended application scenarios:
- Organize teaching video library
- Standardize surveillance video archives
- Manage stock resources
- Automatic test video processing
TIP: It is recommended to combine this script with timing tasks to create an automated file management system. Welcome to share your experience or make suggestions for improvement in the comment section!
The above is the detailed content of batch copying and standardizing naming video files through Python scripts. For more information about copying and renaming video files in Python, please follow my other related articles!