set setting reset

脂肪と糖にはたらくやつ

python でディレクトリ配下の最新のファイル名(フルパス)を取得する

前提

最新かどうかはファイルの最終変更日時 = mtime で判定します。

準備

こんな感じでファイルを作成します

$ for ((i=0;i>10;i++)); do touch $i.txt; sleep 5; done

最終変更日は以下の様になりました。
9.txt の最終変更日時が最も新しいものになっています。

$  stat -f "%N %m" *.txt
0.txt 1465450197
1.txt 1465450202
2.txt 1465450207
3.txt 1465450212
4.txt 1465450217
5.txt 1465450222
6.txt 1465450227
7.txt 1465450232
8.txt 1465450237
9.txt 1465450242

表題のことをする

python スクリプトはこんな感じです。

import os
from glob import glob


def get_latest_modified_file_path(dirname):
  target = os.path.join(dirname, '*')
  files = [(f, os.path.getmtime(f)) for f in glob(target)]
  latest_modified_file_path = sorted(files, key=lambda files: files[1])[-1]
  return latest_modified_file_path[0]


if __name__ == '__main__':
  dirname = "/hoge"
  print(get_latest_modified_file_path(dirname))

実行するとフルパスが取得できます。

$  python get_latest_modified_file_path.py
/hoge/9.txt