Skip to content

Instantly share code, notes, and snippets.

@mal1kc
Last active July 3, 2023 23:22
Show Gist options
  • Save mal1kc/2ac1820e2e9d3d3fea24e6cd52522b55 to your computer and use it in GitHub Desktop.
Save mal1kc/2ac1820e2e9d3d3fea24e6cd52522b55 to your computer and use it in GitHub Desktop.
enumarete filenames with glob pattern
from glob import glob
import os
from pathlib import Path
from pprint import pprint
import re
class Counter :
def __init__(self,name, start=0):
self.name = name
self.num = start
def __call__(self):
self.num += 1
return self.num
def __str__(self):
return f'{self.name}_{self.num}'
def __repr__(self):
return f'{self.__class__.__name__} -> {self.name} : {self.num}'
def __hash__(self):
return hash(self.name)
if __name__ == '__main__':
files_ext = 'png'
imgs_1920 = glob(f"imgs/_1920/*.{files_ext}")
imgs_1920 = [ Path(gorsel) for gorsel in imgs_1920]
old_imgs_1920 = imgs_1920.copy()
new_filenames = []
counters = {}
for img in imgs_1920:
img_main_name = img.stem
img_first_part = img_main_name.split('_')[0]
if img_first_part not in counters:
counters[img_first_part] = Counter(img_first_part,start=1)
else:
counters[img_first_part]()
new_img_main_name = f'{img_first_part}_{counters[img_first_part].num}'
new_filenames.append(img.parent / f'{new_img_main_name}.{files_ext}')
pprint(new_filenames)
pprint(counters)
for old_name, new_name in zip(old_imgs_1920,new_filenames):
if os.rename(old_name, new_name) == None:
print(f'renamed: {old_name} -> {new_name}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment