如何在Python中按创建日期排序的目录列表?

要获取在Python中按创建日期排序的目录列表,可以调用os.listdir()以获得文件名列表。然后为每个调用os.stat()以获取创建时间,最后根据创建时间进行排序。 

示例

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)

输出结果

运行上面的代码将为您提供按创建日期排序的列表,例如,

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