ディレクトリ内のファイルを作成時間の昇順ルールで添え字をつけてリネームするスクリプト
概要
旅行で撮った写真をFacebookにドバっと挙げたかったんだけど、複数のカメラで取ったもんだから、ファイル名がばらばらで、取った順番で挙げたいな~ってモヤモヤしていたので、ディレクトリの中のファイルを作成時間の昇順ベースで添え字をつけてリネームするスクリプト書いたよ。
Before
After
スクリプト
Windows環境でしか、動作確認していません。
(一行目のインタプリタの指定が *nixライク な記述になっているのは気にしないでください。)
#!/usr/bin/env python # coding: utf-8 import os import sys DIR_PATH = "C:\\Users\\hogehoge\\Desktop\\test" RENAME_PATTERN = "IMG_%d%s" # %d: number, %s: extension def is_dir_path(path): """check path whether is existing or dirpath or filepath.""" if os.path.exists(path): if os.path.isdir(path): # directory path return True else: # file path return False else: # doesn't exist return False def get_files(dir_path): """ getting file list """ files = os.listdir(dir_path) return [(os.stat(os.path.join(dir_path, f_name)).st_ctime, \ os.path.join(dir_path, f_name)) \ for f_name in files \ if os.path.isfile(os.path.join(dir_path, f_name))] def rename(num, file_path): """rename!""" root, ext = os.path.splitext(file_path) dir_path = os.path.dirname(file_info[1]) new_name = RENAME_PATTERN % (num, ext) new_file_path = os.path.join(dir_path, new_name) print 'renamed "%s" to "%s"' % (file_path, new_file_path) os.rename(file_path, new_file_path) if __name__ == "__main__": if not is_dir_path(DIR_PATH): sys.exit("ERROR: '%s' is not directory." % DIR_PATH) for i, file_info in enumerate(sorted(get_files(DIR_PATH))): rename(i + 1, file_info[1]) # End of File #
感想
写真が何枚あるかわかるから、アルバムの枚数制限があるFaceBookに挙げるときに便利。