小编典典

如何在python中按创建日期对目录列表进行排序?

python

获取目录中所有文件的列表的最佳方法是什么,按日期排序[创建| 修改],在Windows机器上使用python?


阅读 896

收藏
2020-02-22

共2个答案

小编典典

这@Greg Hewgill是答案的更详细的版本。这是最符合问题要求的。它区分了创建日期和修改日期(至少在Windows上如此)。

#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time

# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
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]))
#NOTE: on Windows `ST_CTIME` is a creation date 
#  but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date

for cdate, path in sorted(entries):
    print time.ctime(cdate), os.path.basename(path)

例:

$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py
2020-02-22
小编典典

过去,我是通过Python脚本确定目录中最后更新的文件的方式:

import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list 
# of files (presumably not including directories)  
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))

这应该可以根据文件mtime执行你想要的操作。

编辑:请注意,如果需要,还可以使用os.listdir()代替glob.glob()-我在原始代码中使用glob的原因是我想使用glob仅搜索具有特定集合的文件文件扩展名,glob()更适合。要使用listdir,结果如下所示:

import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))
2020-02-22