40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
##########
|
|
# Rename fonctions for scripting on the fly
|
|
#
|
|
import os
|
|
import math
|
|
from pathlib import Path
|
|
|
|
def is_picture(entry):
|
|
"""Return True if DirEntry is a picture"""
|
|
extension = ("jpg","png")
|
|
for ext in extension:
|
|
if entry.name.endswith('.'+ext):
|
|
return True
|
|
return False
|
|
|
|
def get_pictures(path):
|
|
"""Scan directory for pictures return DirEntry list of files"""
|
|
pictures = []
|
|
with os.scandir(path) as it:
|
|
for entry in it:
|
|
if not entry.name.startswith('.') \
|
|
and entry.is_file(follow_symlinks=False) \
|
|
and is_picture(entry):
|
|
pictures.append(entry)
|
|
return pictures
|
|
|
|
def rename(entries, reverse=False):
|
|
"""Rename file"""
|
|
entries = sorted(entries, key=lambda entry: entry.name, reverse=reverse)
|
|
digit_length = int(math.log10(len(entries)) + 1)
|
|
renamed = {}
|
|
for i, entry in enumerate(entries):
|
|
renamed[entry] = '{number:0{width}d}{ext}'.format(number=i,width=digit_length,ext=Path(entry.path).suffix)
|
|
for src, dst in renamed.items():
|
|
os.rename(src, dst)
|
|
|
|
if __name__ == '__main__':
|
|
entries = get_pictures('/home/nicolas/tmp')
|
|
rename(entries, reverse=True)
|