理想の書き方
# file_to_dir_p4.py
import os
import datetime
import shutil
from pathlib import Path
def datetime_to_y_m_d(dt):
"""日時を「年_月_日」に変換
"""
return dt.strftime("%Y_%m_%d")
def get_file_mod_datetime(file_path):
""" ファイルの更新日時を取得
"""
mod_dt = os.path.getmtime(str(file_path))
return datetime.datetime.fromtimestamp(mod_dt)
def copy_file_to_dir(dir_path, file_path):
"""ファイルをディレクトリにコピー
"""
dir_path.mkdir(exist_ok=True)
shutil.copy2(str(file_path), str(dir_path))
def main():
current_dir = Path(".")
jpeg_date = Path("./jpeg_dates")
jpeg_date.mkdir(exist_ok=True)
for file in current_dir.glob("*.jpg"):
mod_dt = get_file_mod_datetime(file)
date_dir = jpeg_date / datetime_to_y_m_d(mod_dt)
copy_file_to_dir(date_dir, file)
if __name__ == '__main__':
main()