How to sort files by modification date in Python
You can use sorted()
to sort the files, and use key=lambda t: os.stat(t).st_mtime
to sort by modification time. This will sort with ascending modification time (i.e. most recently modified file last).
In case you want to sort with descending modification time (i.e. most recently modified file first), use key=lambda t: -os.stat(t).st_mtime
Full example:
# List all files in the home directory
files = glob.glob(os.path.expanduser("~/*"))
# Sort by modification time (mtime) ascending and descending
sorted_by_mtime_ascending = sorted(files, key=lambda t: os.stat(t).st_mtime)
sorted_by_mtime_descending = sorted(files, key=lambda t: -os.stat(t).st_mtime)