Created
March 4, 2023 14:43
-
-
Save Denperidge/bffbdce0b247a8dbdc8483e0b8b51c28 to your computer and use it in GitHub Desktop.
Hope to move this to a dedicated script repo soon! But for backups sake:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from glob import glob | |
from pathlib import Path | |
from sys import argv | |
from os import system | |
from re import search, RegexFlag | |
from datetime import datetime | |
#exiftool -r "-FileCreateDate<DateTimeOriginal" "-FileModifyDate<FileCreateDate" "%1%" | |
DATE_FORMAT_STRING = "%Y%m%d_%H%M%S__" # == yyyyMMdd_HHmmss__ | |
NAME_FORMATTED = r"[^a-z]{1,}_{2}" | |
MODES = ["prepend", "undo"] | |
DIRECTORY = "D:/Pictures/**/*" | |
args = [arg.lower() for arg in argv] | |
apply = "--apply" in args | |
def prepend(filename): | |
path = Path(filename).absolute() | |
if path.name.startswith("IMG_"): | |
# st_mtime is last modified | |
file_date = datetime.fromtimestamp(path.stat().st_mtime) | |
new_path = path.with_name(file_date.strftime(DATE_FORMAT_STRING) + path.name) | |
print(f""" | |
Renaming: | |
{path} | |
--> {new_path} | |
""") | |
if apply: | |
# I think this was for some iphone weird stuff | |
system(f'exiftool -r "-FileCreateDate<DateTimeOriginal" "-FileModifyDate<FileCreateDate" "{path}"') | |
path.rename(new_path) | |
else: | |
print(f"NOT processing {path.name}") | |
def undo(filename): | |
path = Path(filename).absolute() | |
should_be_undo_ed = search(NAME_FORMATTED, path.name, RegexFlag.IGNORECASE) | |
if should_be_undo_ed is not None: | |
to_remove = should_be_undo_ed.group(0) | |
new_path = path.with_name(path.name.replace(to_remove, "")) | |
print(f""" | |
Renaming: | |
{path} | |
--> {new_path} | |
""") | |
if apply: | |
path.rename(new_path) | |
else: | |
print(f"SKIPPING {path.name}") | |
print( | |
f""" | |
This script can: | |
{MODES[0]}: prepend {DATE_FORMAT_STRING} to files | |
{MODES[1]}: remove that prepend | |
""") | |
mode = input("Select mode: ").lower().strip() | |
if mode not in MODES: | |
exit(0) | |
# Prepend | |
if mode == MODES[0]: | |
handle_file = prepend | |
# Undo prepend | |
elif mode == MODES[1]: | |
handle_file = undo | |
files = glob(DIRECTORY, recursive=True) | |
for file in files: | |
handle_file(file) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment