videocut/strip_suffix.py

84 lines
2.4 KiB
Python

import os
import re
import sys
import glob
def strip_duplicate_suffix(filename):
"""Strips OS-generated duplicate suffixes like ' (2)', ' (3)' from a filename.
Examples:
'video (2).mp4' -> 'video.mp4'
'video (3).mp4' -> 'video.mp4'
'video.mp4' -> 'video.mp4'
"""
name, ext = os.path.splitext(filename)
cleaned = re.sub(r'\s+\(\d+\)$', '', name)
return cleaned + ext
def main():
# 1. Check arguments
if len(sys.argv) < 2:
print("Usage: python strip_suffix.py <path_to_folder> [--apply]")
print(" By default, runs in dry-run mode (preview only).")
print(" Add --apply to actually rename the files.")
return
# 2. Parse arguments
raw_input = sys.argv[1].strip(' "\'')
input_dir = os.path.abspath(raw_input)
apply_mode = "--apply" in sys.argv
if not os.path.isdir(input_dir):
print(f"Error: '{input_dir}' is not a directory.")
return
# 3. Find all files in the directory
files = os.listdir(input_dir)
files.sort()
rename_count = 0
skip_count = 0
print(f"Scanning: {input_dir}")
print(f"Mode: {'APPLY (will rename files)' if apply_mode else 'DRY-RUN (preview only)'}")
print("-" * 50)
for filename in files:
# Only process files, not directories
filepath = os.path.join(input_dir, filename)
if not os.path.isfile(filepath):
continue
clean_name = strip_duplicate_suffix(filename)
if clean_name != filename:
clean_path = os.path.join(input_dir, clean_name)
# Check if the target name already exists
if os.path.exists(clean_path):
print(f" SKIP: '{filename}' -> '{clean_name}' (target already exists)")
skip_count += 1
continue
if apply_mode:
os.rename(filepath, clean_path)
print(f" RENAMED: '{filename}' -> '{clean_name}'")
else:
print(f" WOULD RENAME: '{filename}' -> '{clean_name}'")
rename_count += 1
print("-" * 50)
if rename_count == 0:
print("No files with duplicate suffixes found.")
else:
action = "Renamed" if apply_mode else "Would rename"
print(f"{action} {rename_count} file(s). Skipped {skip_count} file(s).")
if not apply_mode:
print("\nRun again with --apply to actually rename the files.")
if __name__ == "__main__":
main()