0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

フォルダのタイムスタンプをフォルダ内のファイルと合わせる

Posted at

Windows環境でフォルダをコピーして移動したりすると
フォルダの更新日がコピー操作をした日時になってファイルの管理が面倒なので
フォルダ内のファイルに合わせるスクリプトを作ってみた

実行ファイル形式のものはともかく スクリプトがすぐに見つけられなかったため自分用メモ

import time
import os

# フォルダのパス raw文字指定なので エクスプローラーからコピペ可
folder_path = r"D:\TempItems"

def set_folder_timestamp(folder_path):
    latest_timestamp = 0
    for file in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file)
        if os.path.isfile(file_path):
            # 更新日の取得
            timestamp = os.path.getmtime(file_path)
            if timestamp > latest_timestamp:
                latest_timestamp = timestamp
        elif os.path.isdir(file_path):
            set_folder_timestamp(file_path)
    # フォルダのタイムスタンプを設定する
    if latest_timestamp != 0:
        os.utime(folder_path, (latest_timestamp, latest_timestamp))

set_folder_timestamp(folder_path)

指定したフォルダの下を再帰的に辿るようにはしている
再帰呼び出しで下の階層の更新日を戻り値にしておいて比較してもいいかも

因みに最近話題のChatGPTに最初書かせてみたのだけれど関数の再帰呼び出しはしてくれなかったので
結局自分で書いた方が速かった

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?