Files
custom_scripts/rename_to_first4.py
2025-11-17 00:41:24 +01:00

48 lines
1.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""
rename_to_first4.py
Usage:
python3 rename_to_first4.py <directory>
Renames each file in <directory> so its name becomes the first
four characters of the original filename (before the extension).
Keeps the file extension and avoids overwriting existing files.
"""
import os
import sys
from pathlib import Path
def main():
if len(sys.argv) != 2:
print("Usage: rename_to_first4.py <directory>")
sys.exit(1)
directory = Path(sys.argv[1])
if not directory.is_dir():
print(f"Error: '{directory}' is not a directory.")
sys.exit(1)
for f in directory.iterdir():
if not f.is_file():
continue
stem = f.stem[:4] # first 4 letters of filename (no extension)
new_name = f"{stem}{f.suffix}"
new_path = directory / new_name
# avoid overwriting existing files
counter = 1
while new_path.exists():
new_name = f"{stem}_{counter}{f.suffix}"
new_path = directory / new_name
counter += 1
print(f"Renaming: {f.name} -> {new_name}")
f.rename(new_path)
print("✅ Done renaming all files.")
if __name__ == "__main__":
main()