Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stakiran/93b8a35922e42e35a4a4c97487ab83d7 to your computer and use it in GitHub Desktop.
Save stakiran/93b8a35922e42e35a4a4c97487ab83d7 to your computer and use it in GitHub Desktop.
170911_092827 Windows におけるフォルダのタイムスタンプ(最終更新日時)の挙動

ファイルフォルダ監視ツール作りたくて調べた。

実験スクリ

Pythonでファイルの最終更新時間を取得する方法 | 遍歴プログラマ日記 を参考に。

# -*- coding: utf-8 -*-

import datetime
import os
from time import sleep

def get_lastmodified(filepath):
    return os.stat(filepath).st_mtime

def get_lastaccessed(filepath):
    return os.stat(filepath).st_atime

def lastmodified_to_dt(lastmodified):
    return datetime.datetime.fromtimestamp(lastmodified)

print 'file'
print 'access %.f' % get_lastaccessed('a.txt')
print 'modify %.f' % get_lastmodified('a.txt')
print 'folder'
print 'access %.f' % get_lastaccessed('a')
print 'modify %.f' % get_lastmodified('a')

実験:

  • 適当なディレクトリに a.txt と a\a.txt を作り、上記スクリを置く
  • 上記スクリを実行
  • a.txt をいじる
  • 上記スクリを実行
  • 最終アクセス時間、最終修正時間はどうなってる?

結果

Q: st_mtime あるいは st_atime を用いて「変更された」をゲットできるか?

A: 部分的なら可能。詳しくは以下。

  • ファイル
    • ⭕ 中身が編集された時
    • ❌ プロパティが変更された時、リネームされた時
  • フォルダ
    • ⭕ 配下のファイルが新規、削除、リネームされた時
    • ❌ フォルダ内ファイルを編集された時、フォルダのプロパティが更新された時

見解

結果を踏まえると、「st_mtime あるいは st_atime を用いてファイル監視を作りたい場合、ファイル内容が変更された時しか検出できない。同上、フォルダ監視を作りたい場合、配下のファイルが CUD された時しか検出できない」と言える。

一番痛いのは フォルダ内ファイルを編集したとしてもそのフォルダの更新がわからない ってことか。st_mtime や st_atime を見るだけではダメってこと。フォルダだけでなくファイルのそれらもチェックしなきゃいけないってことか。だるい。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment