Skip to content

Instantly share code, notes, and snippets.

@movalex
Last active August 3, 2023 14:41
Show Gist options
  • Select an option

  • Save movalex/2fc9c4d873794cc313c8d20c01b8bfd9 to your computer and use it in GitHub Desktop.

Select an option

Save movalex/2fc9c4d873794cc313c8d20c01b8bfd9 to your computer and use it in GitHub Desktop.
Rename files based on Windows file tag
from pathlib import Path
import os
import shutil
from win32com.propsys import propsys
FOLDER = Path(".")
OUTPUT = "TEL"
pk = propsys.PSGetPropertyKeyFromName("System.Keywords")
def get_tags(image):
ps = propsys.SHGetPropertyStoreFromParsingName(image)
keywords = ps.GetValue(pk).GetValue()
return keywords
def rename_files(copied_file: str, destination_name: Path):
try:
Path(copied_file).rename(destination_name)
except FileExistsError:
print("File exists, rename skipped")
def copy_files(file, tag=None, overwrite=True):
destination_folder = tag
new_name = f"{tag}_{file.name}"
if tag is None:
new_name = file.name
destination_folder = "OTHER"
out_folder = Path(OUTPUT, destination_folder)
out_folder.mkdir(exist_ok=True, parents=True)
copied = shutil.copy(file, str(out_folder))
print("copied: ", copied)
if tag:
dest_file = out_folder / new_name
if dest_file.exists() and overwrite is True:
dest_file.unlink()
rename_files(copied, dest_file)
def process():
Path(OUTPUT).mkdir(exist_ok=True, parents=True)
for file in FOLDER.glob("*.jpg"):
image = str(file.absolute())
tags = get_tags(image)
try:
for tag in tags:
copy_files(file, tag)
except TypeError:
copy_files(file)
if __name__ == "__main__":
process()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment