Created
July 18, 2018 15:54
-
-
Save rene-d/b811f3fe44965362fd0a61b0befb1f1f to your computer and use it in GitHub Desktop.
Sort subdirectories of a directory by the most recent file dates with them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
import os | |
import pathlib | |
import argparse | |
import datetime | |
from collections import defaultdict | |
parser = argparse.ArgumentParser(description='Sort subdirectories by most recent files within them') | |
parser.add_argument('-v', '--verbose', help="be verbose", action='store_true') | |
parser.add_argument('dirs', nargs='+', metavar='DIR', help="directory to scan") | |
args = parser.parse_args() | |
for path in args.dirs: | |
f = pathlib.PosixPath(path) | |
n = len(f.parts) | |
print(path) | |
latest = defaultdict(lambda: 0) | |
for f in pathlib.Path(path).glob('**/*'): | |
assert len(f.parts) > n | |
if len(f.parts) == n + 1 and not f.is_dir(): | |
continue | |
st = f.lstat() | |
# t = max(st.st_ctime, st.st_mtime) | |
t = st.st_mtime | |
part = f.parts[n] | |
latest[part] = max(t, latest[part]) | |
if args.verbose: | |
print("{:30} {} {}".format(part, datetime.datetime.fromtimestamp(t).ctime(), os.path.join(*f.parts[n:]))) | |
latest = sorted([(v, k) for k, v in latest.items()]) | |
for v, k in latest: | |
print(" {} {}".format(datetime.datetime.fromtimestamp(v).ctime(), k)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment