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")
if they just want files that end in
.txt
you might use grep, something like:ls -Art | grep -E '.txt$' | tail -n 1