如何对目录中的文件名排序并在文件名开头添加序号?附示例文件
Solution: Python Script to Sort and Rename Files with Sequential Numbers
Got it, let's solve this. You need to take all the video files in a specific folder, sort them logically, and prepend a sequential number to each filename—even if some already have numbers at the start. Here's a robust Python script that handles this, plus a walkthrough of how it works:
import os def sort_and_rename_files(target_dir): # Define the video file extensions we want to process (case-insensitive) video_extensions = ('.MKV', '.MP4', '.mkv', '.mp4') # Grab all video files from the target directory video_files = [f for f in os.listdir(target_dir) if f.endswith(video_extensions)] # Custom sort key: strip leading numbers/punctuation to sort by the actual title def get_sort_key(filename): # Skip past any leading digits, dashes, dots, or spaces to get the core title for i, char in enumerate(filename): if not (char.isdigit() or char in '-., '): return filename[i:].lower() return filename.lower() # Sort the files using our custom key sorted_files = sorted(video_files, key=get_sort_key) # Rename each file with sequential numbering for idx, filename in enumerate(sorted_files, start=1): # Split filename into base name and extension name, ext = os.path.splitext(filename) # Clean up existing leading numbers/punctuation from the original name cleaned_name = name for i, char in enumerate(cleaned_name): if not (char.isdigit() or char in '-., '): cleaned_name = cleaned_name[i:] break # Create the new filename with the sequential number new_filename = f"{idx}-{cleaned_name}{ext}" old_path = os.path.join(target_dir, filename) new_path = os.path.join(target_dir, new_filename) # Avoid overwriting existing files by adding a counter if needed counter = 1 while os.path.exists(new_path): new_filename = f"{idx}-{cleaned_name}_{counter}{ext}" new_path = os.path.join(target_dir, new_filename) counter += 1 # Perform the rename and log the change os.rename(old_path, new_path) print(f"Renamed: {filename} -> {new_filename}") # Replace this with your actual target directory path target_directory = "/path/to/your/video/folder" sort_and_rename_files(target_directory)
How This Works:
- Target Directory: Swap out the
target_directoryvalue with the full path to your video folder. - File Filtering: The script only processes
.MKVand.MP4files (works with both uppercase and lowercase extensions). - Smart Sorting: The custom sort key ignores leading numbers, dashes, or dots, so files like
2.Kaggle Deep Learning - YouTube.MP4andKaggle Deep Learning 3 - YouTube.MP4get grouped together correctly. - Safe Renaming: If a new filename already exists (unlikely but possible), the script adds a counter suffix (e.g.,
_1,_2) to avoid overwriting files. - Clean Titles: Existing leading numbers/punctuation are stripped from the original filename before adding the new sequential number, so you won't end up with messy names like
3-2.Kaggle Deep Learning....
Example Output:
For your sample files, after running the script, you’ll get clean, numbered filenames like:
1-intro to deeplearning and computer vision.MKV2-Kaggle Deep Learning - YouTube.MP43-Convolutional Neural Networks - Fun and Easy Machine Learning - YouTube.MP44-Convolutional Neural Networks - The Math of Intelligence (Week 4)YouTube.MKV5-Introduction to Deep Learning- What Are Convolutional Neural Networks- YouTube.MP46-Kaggle Deep Learning 3 - YouTube.MP47-Kaggle Deep Learning 4 - YouTube.MP48-Kaggle Deep Learning 5 Data Augmentation - YouTube.MP49-Kaggle Deep Learning 6 - YouTube.MP4- ...and so on for the rest of your files
Quick reminder: Always back up your files before running renaming scripts—better safe than sorry!
内容的提问来源于stack exchange,提问作者ryitesh
相关产品推荐
相关产品推荐

