如何在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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短