Computer >> Computer tutorials >  >> Programming >> Python

How do you get a directory listing sorted by creation date in Python?


To get a directory listing sorted by creation date in Python, you can call os.listdir() to get a list of the filenames. Then call os.stat() for each one to get the creation time and finally sort against the creation time. 

example

import os
import time
import sys
from stat import S_ISREG, ST_CTIME, ST_MODE
dir_path = '.'
# get all entries in the directory
entries = (os.path.join(dir_path, file_name) for file_name in os.listdir(dir_path))
# Get their stats
entries = ((os.stat(path), path) for path in entries)
# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))
print(entries)

Output

Running the above code will give you listing sorted by creation date, for example,

Mon Oct 23 18:01:25 2017 sorted_ls.py