Find the newest folder in a directory in Python
One liner to find latest
# Find latest
import os, glob
max(glob.glob(os.path.join(directory, '*/')), key=os.path.getmtime)
One liner to find n'th latest
# Find n'th latest
import os, glob
sorted(glob.glob(os.path.join(directory, '*/')), key=os.path.getmtime)[-n]
There is no actual trace of the "time created" in most OS / filesystems: what you get as mtime
is the time a file or directory was modified (so for example creating a file in a directory updates the directory's mtime) -- and from ctime
, when offered, the time of the latest inode change (so it would be updated by creating or removing a sub-directory).
Assuming you're fine with e.g. "last-modified" (and your use of "created" in the question was just an error), you can find (e.g.) all subdirectories of the current directory:
import os
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
and get the one with the latest mtime (in Python 2.5 or better):
latest_subdir = max(all_subdirs, key=os.path.getmtime)
If you need to operate elsewhere than the current directory, it's not very different, e.g.:
def all_subdirs_of(b='.'):
result = []
for d in os.listdir(b):
bd = os.path.join(b, d)
if os.path.isdir(bd): result.append(bd)
return result
the latest_subdir
assignment does not change given, as all_subdirs
, any list of paths
(be they paths of directories or files, that max
call gets the latest-modified one).