LoginSignup
8
9

More than 5 years have passed since last update.

ファイルの更新日時でソートする

Posted at

ファイルを更新日時でソートします。

Python 版

mtime.py
# coding: utf-8

import os
import time
import datetime

def sort_mtime(rootdir):
    xs = []
    for root, dir, files in os.walk(rootdir):
        for f in files:
            path = os.path.join(root, f)
            xs.append((os.path.getmtime(path), path))

    for mtime, path in sorted(xs):
        name = os.path.basename(path)
        t = datetime.datetime.fromtimestamp(mtime)
        print(t, name)

def main():
    sort_mtime('.')

if __name__ == '__main__':
    main()

実行結果です。

% python3 mtime.py
2015-01-17 13:52:15 mtime.py
2015-01-17 13:58:36 readme.md
2015-01-17 14:17:48 mtime.rb

Ruby 版

mtime.rb
require 'find'

def sort_mtime(rootdir)
  xs = []
  Find.find(rootdir) { |f|
    xs << [File::mtime(f), f] if File::file?(f)
  }
  xs.sort.each { |mtime, f|
    puts "#{mtime} #{f}"
  }
end

if __FILE__ == $0
  sort_mtime('.')
end

実行結果です。

% ruby mtime.rb
2015-01-17 13:52:15 +0900 ./mtime.py
2015-01-17 13:58:36 +0900 ./readme.md
2015-01-17 14:17:48 +0900 ./mtime.rb
8
9
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
8
9