Find and append file path

Tim Chase python.list at tim.thechases.com
Thu Jan 12 10:39:34 EST 2017


On 2017-01-12 19:28, Iranna Mathapati wrote:
> Example:
> CLI Input: /root/user/branches/xyz
> 
> find latest file and append to CLI path:
> "/root/user/branches/xyz/Apple"


I've used something like the below to find the most recent file in a
directory tree (it also works for pulling other attributes like the
file-size from os.stat() results).

-tkc


import os
from operator import attrgetter

def dir_iter(root):
    for fullpath in (
            os.path.join(path, dir_)
            for path, dirs, files in os.walk(root)
            for dir_ in dirs
            ):
        if os.path.isdir(fullpath):
            yield fullpath

def find_latest(root,
        which_time=attrgetter("st_mtime")
        ):
    return max(dir_iter(root),
        key=lambda fullpath: which_time(os.stat(fullpath))
        )

if __name__ == "__main__":
    from sys import argv
    if len(argv) > 1:
        root = argv[1]
    else:
        root = '.'
    print(find_latest(root))
    print(find_latest(root, which_time=attrgetter("st_ctime")))


More information about the Python-list mailing list