你如何在python中获得按创建日期排序的目录列表? [英] How do you get a directory listing sorted by creation date in python?
问题描述
获取目录中所有文件列表的最佳方法是什么,按日期排序[创建|修改],在 Windows 机器上使用 python?
What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?
推荐答案
更新:在 Python 3 中按修改日期对 dirpath
的条目进行排序:
Update: to sort dirpath
's entries by modification date in Python 3:
import os
from pathlib import Path
paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)
(将 @Pygirl 的回答放在这里以提高知名度)
(put @Pygirl's answer here for greater visibility)
如果您已经有一个文件名列表files
,那么在 Windows 上按创建时间对其进行就地排序(确保该列表包含绝对路径):
If you already have a list of filenames files
, then to sort it inplace by creation time on Windows (make sure that list contains absolute path):
files.sort(key=os.path.getctime)
例如,使用 glob
可以获得的文件列表,如 @Jay 的回答所示.
The list of files you could get, for example, using glob
as shown in @Jay's answer.
旧答案这是 @Greg Hewgill
的回答.是最符合题型要求的.它区分了创建日期和修改日期(至少在 Windows 上是这样).
old answer
Here's a more verbose version of @Greg Hewgill
's answer. It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on 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
这篇关于你如何在python中获得按创建日期排序的目录列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!