Skip to content

Instantly share code, notes, and snippets.

@nobucshirai
Created February 13, 2025 02:46
Show Gist options
  • Save nobucshirai/0890fff03e246c847fac35bdcbd05136 to your computer and use it in GitHub Desktop.
Save nobucshirai/0890fff03e246c847fac35bdcbd05136 to your computer and use it in GitHub Desktop.
Timestamp-based Renaming: A script that renames files by adding a timestamp derived from their last modification time.
#!/usr/bin/env python3
import os
import re
import argparse
from datetime import datetime
def timestamp_renamer(files, custom_prefix=None):
for file_path in files:
# Extract the file extension and convert it to lowercase
_, ext = os.path.splitext(file_path)
ext = ext[1:].lower()
# Replace "jpeg" with "jpg"
if ext == "jpeg":
ext = "jpg"
# If a custom prefix is provided, use it; otherwise, pick one based on the extension
if custom_prefix:
prefix = custom_prefix
else:
if ext == "png":
prefix = "Screenshot_"
elif ext in ["jpg", "heic"]:
prefix = "Photo_"
elif ext in ["mp4", "mov"]:
prefix = "Video_"
elif ext in ["mp3", "m4a"]:
prefix = "Audio_"
elif ext in ["pdf", "doc", "docx"]:
prefix = "Document_"
elif ext in ["csv", "xls", "xlsx"]:
prefix = "Table_"
elif ext in ["ppt", "pptx"]:
prefix = "Slide_"
elif ext == "html":
prefix = "Webpage_"
elif ext in ["txt", "rtf", "odt"]:
prefix = "Text_"
else:
prefix = "File_"
# Pattern to find any existing suffix in the filename
pattern = r'_at_[0-9]{2}\.[0-9]{2}\.[0-9]{2}(_[a-zA-Z0-9_]+)\.' + re.escape(ext)
match = re.search(pattern, file_path)
suffix = match.group(1) if match else ""
# Get the timestamp of the file
timestamp = datetime.fromtimestamp(os.path.getmtime(file_path)).strftime("%Y-%m-%d_at_%H.%M.%S")
# Generate the new name and check for collisions
new_name = f"{prefix}{timestamp}{suffix}.{ext}"
if file_path != new_name:
count = 2
while os.path.exists(new_name):
new_name = f"{prefix}{timestamp}{suffix}_{count}.{ext}"
count += 1
# Rename the file
os.rename(file_path, new_name)
print(f"Renamed {file_path} to {new_name}")
if __name__ == "__main__":
# Initialize argparse for command-line options
parser = argparse.ArgumentParser(description="Rename files to include their modification timestamp.")
parser.add_argument("files", metavar="FILE", type=str, nargs="+", help="one or more files to rename")
parser.add_argument(
"--prefix", "-p",
type=str,
default=None,
help="Custom prefix to use for the renamed files (overrides extension-based prefix)."
)
# Parse the command-line arguments
args = parser.parse_args()
# Call the function with the parsed arguments
timestamp_renamer(args.files, custom_prefix=args.prefix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment