Last active
December 31, 2019 18:27
-
-
Save 3110/56dcf198a9de3b823e67e93621dc9f21 to your computer and use it in GitHub Desktop.
ファイル名に連番を振りながらリネームします
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- code: utf-8 -*- | |
# | |
# python rename.py [-c|--count count] [-d|--dir directory] [-n|--dry-run] [-t|--timestamp] regex target | |
# | |
# count: 連番の開始番号。デフォルトは0 | |
# directory: リネームするファイルがあるディレクトリ | |
# regex: リネームするファイルにマッチする正規表現 | |
# target: 文字列のformatと同じ書式。引数の0番目は連番,1番目以降は前方参照の値が入る | |
# | |
# python rename.py 'filename-(\w+).jpg' 'hoge-{1}-{0:0>4}.txt' | |
# | |
import datetime | |
import pathlib | |
import re | |
import shutil | |
def rename(dir, regex, target, count, dry_run, key): | |
for p_file in sorted([p for p in pathlib.Path(dir).glob('**/*')], key=key): | |
timestamp = datetime.datetime.fromtimestamp(p_file.stat().st_ctime) | |
m = re.search(regex, p_file.name) | |
if m: | |
p_target_file = p_file.parent / target.format(count, *m.groups()) | |
count += 1 | |
if dry_run: | |
print(f'dry_run: {timestamp}: {p_file} -> {p_target_file}') | |
else: | |
print(f'{timestamp}: {p_file} -> {p_target_file}') | |
shutil.move(p_file, p_target_file) | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser(description='ファイルをリネームします') | |
parser.add_argument('-c', '--count', nargs='?', type=int, default=0, help='連番の開始番号') | |
parser.add_argument('-d', '--dir', nargs='?', default='.', help='ファイルがあるディレクトリ') | |
parser.add_argument('-n', '--dry-run', action='store_true', help='実行の様子を見る') | |
parser.add_argument('-t', '--timestamp', action='store_true', help='タイムスタンプでソートする') | |
parser.add_argument('regex', help='リネームするファイルにマッチする正規表現') | |
parser.add_argument('target', help='リネーム後のファイル名を指定するフォーマット') | |
args = parser.parse_args() | |
if args.timestamp: | |
key = lambda c: c.stat().st_ctime | |
else: | |
key = lambda c: c | |
rename(args.dir, args.regex, args.target, args.count, args.dry_run, key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment