SIGMA DP2をMacにUSBケーブルで繋げて撮影した画像データをSDからハードディスクに現在日付名のフォルダを作って移動してファイル名を作成日でリネームしちゃうスクリプト
- ハードディスクの指定パスに現在年月日名のディレクトリを作成(HD = '/Users/username/path_of_copy_to')
- x3f、jpgのファイルを移動
- 作成日+拡張子でリネーム
- コピー先(HD)に同名ファイルがある場合は作成日の後に長い数字の文字列を追加
- コピー元(SD)と先(HD)を比較確認してコピー元のファイルを削除。
※実行時のリスクは自己責任で宜しくお願いします。
(環境:MacOSX10.5, python2.5)
コード
#!/usr/bin/env python # *-# -*- coding: utf-8 -*- import os import re import os.path import time import shutil import filecmp from datetime import date SD = '/Volumes/SIGMA DP2/DCIM/100SIGMA/' HD = '/Users/username/path_of_copy_to' def get_file_name(dir_path, re_pattern): os.chdir(dir_path) file_arr = os.listdir(dir_path) re_ext = re.compile(re_pattern, re.I) return [f for f in file_arr if os.path.isfile(f) and re_ext.search(f)] def is_with_a_some_dir_name(dir_path, check_dir_name): return check_dir_name in os.listdir(dir_path) def get_today_time(): return date.today().strftime("%Y%m%d") def make_today_dir(dir_path): today = get_today_time() if not is_with_a_some_dir_name(dir_path, today): make_path = os.path.join(dir_path, today) os.mkdir(make_path) return today def get_creation_date(file_path): osstat = os.stat(file_path) srcdates = osstat[-2] get_ctime = time.localtime(srcdates) return time.strftime("%Y%m%d-%H%M%S", get_ctime) def split_name_ext(file_name): name, ext = os.path.splitext(file_name) return [name, ext] def add_time_when_is_some_name(dir_path, name): is_file = name in [split_name_ext(f)[0] for f in os.listdir(dir_path)] if is_file: name = "%s_%d" % (name, int(time.time()*10000)) return name def get_dict_of_from_f_and_date_name_f(from_dir_path, to_dir_path): sd_file_arr = get_file_name(from_dir_path, r"\.(x3f|jpg)$") creation_date_name_arr = [] for f_name in sd_file_arr: name, ext = split_name_ext(f_name) m_name = get_creation_date(os.path.join(from_dir_path, f_name)) m_name = add_time_when_is_some_name(to_dir_path, m_name) creation_date_name_arr.append(m_name + ext) return dict(zip(sd_file_arr, creation_date_name_arr)) def copy_file(from_dir_path, to_dir_path, file_dict, is_remove_from_file): for from_name, to_name in file_dict.items(): from_f = os.path.join(from_dir_path, from_name) to_f = os.path.join(to_dir_path, to_name) shutil.copy2(from_f, to_f) if is_remove_from_file and filecmp.cmp(from_f, to_f): os.remove(from_f) def main(from_dir_path, to_dir_path, is_remove_from_file=True): if os.listdir(from_dir_path): today_dir = make_today_dir(to_dir_path) path_of_hd_today_d = os.path.join(to_dir_path, today_dir) file_dict = get_dict_of_from_f_and_date_name_f(from_dir_path, path_of_hd_today_d) copy_file(from_dir_path, path_of_hd_today_d, file_dict, is_remove_from_file) return "%d files done!!" % len(file_dict) if __name__ == '__main__': print main(SD, HD)
Macでダイアログ出すときは
- 最後の2行を下記に書き換え
if __name__ == '__main__': import EasyDialogs try: result = main(SD, HD) except OSError, strerror: result = str(strerror) EasyDialogs.Message(result)