获取目录中所有文件列表的最佳方法是什么,按日期排序 [创建 | 修改],在Windows机器上使用python?
更新dirpath:在 Python 3 中按修改日期对 的条目进行排序:
dirpath
import os from pathlib import Path paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)
如果您已经有一个文件名列表files,则在 Windows 上按创建时间对其进行就地排序(确保该列表包含绝对路径):
files
files.sort(key=os.path.getctime)
旧答案更详细版本。是最符合题目要求的。它区分了创建日期和修改日期(至少在 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