[PYTHON] Sort by file modification date

Sort files by modification date.

Python version

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()

This is the execution result.

python


% 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 version

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

This is the execution result.

python


% 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

Recommended Posts

Sort by file modification date
Sort by date in python
Sort by dict type value value
Sort the file names obtained by Python glob in numerical order
[Python] Sort iterable by multiple conditions
Summary of restrictions by file system