Lets say I want to find the youngest/newest *.txt file inside a folder, for example /tmp/? I wrote this little python script for this, but are there better ways to do it?

By youngest I mean the file with the least recent change or creation date? All files have these timestamps. But could I also watch the filesystems folder for file creation events?

import os
import glob

def find_newest_file_type(glob_path):
    # youngest file has biggest timestamp
    youngest = -10
    ultpath = "file_does_not_exist0xfadfadsfadfads.asdfajsdklfj"
    for file in  glob.iglob(glob_path):
        mtime = os.path.getmtime(file)
        if mtime > youngest:
            youngest = mtime
            ultpath = file
    return ultpath

newest = find_newest_file_type("/tmp/*.txt")
  • RanzigFettreduziert@feddit.org
    link
    fedilink
    English
    arrow-up
    5
    ·
    2 months ago
    ls -Art | tail -n 1
    

    This will return the latest modified file or directory. Not very elegant, but it works.

    Used flags:

    -A list all files except . and …

    -r reverse order while sorting

    -t sort by time, newest first

    Source