#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2022/06/06 20:34:30 +0900> """ Rename files based on file size usage: python sortrename.py PATH0 PATH1 PATH2 hoge_1920x1080_2_.jpg -> hoge_1920x1080_2.jpg hoge_1920x1080_2.jpg -> hoge_1920x1080_3.jpg hoge_1920x1080_3.jpg -> hoge_1920x1080_4.jpg Windows10 x64 21H2 + Python 3.9.13 64bit """ import sys import os import re def main(): renamelist = [] cnt = len(sys.argv) if cnt <= 2: print("Error : Please select two or more files.") else: lst = [] for i in range(1, cnt): path = sys.argv[i] size = os.path.getsize(path) lst.append([path, size]) slist = sorted(lst, key=lambda x: x[1]) count = len(slist) + 1 for v in slist: path, size = v dirname = os.path.dirname(path) filename = os.path.basename(path) newfile = re.sub("_\d_*\.jpg", "_%d.jpg" % count, filename) newpath = os.path.join(dirname, newfile) print("%s -> %s : %d byte" % (filename, newfile, size)) renamelist.append([path, newpath]) count -= 1 if len(renamelist) >= 1: v = input("\nRename ? (Y/n)") if v == "y" or v == "Y" or v == "": for v in renamelist: oldpath, newpath = v os.rename(oldpath, newpath) print("\n%d file renamed." % len(renamelist)) else: print("\nCancel.") v = input("\nPush any key") if __name__ == '__main__': main()