python - 如何在 python 中获得按创建日期排序的目录列表?

标签 python windows directory

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

最佳答案

我过去曾为 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))

关于python - 如何在 python 中获得按创建日期排序的目录列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/168409/

相关文章:

java - 删除以 "."android开头的文件夹

python - 考虑顺序对 pandas 列执行累积计数

windows - GHC::在 Windows 上再次链接 sqlite3 失败

windows - Windows 中的 curl 读取函数返回了有趣的值

node.js - Gulp安装: 'fs: re-evaluating native module sources is not supported' and node-sass errors

java - 损坏的 NTFS 文件夹 java

java - 从 file.getpath() Java 中删除一些文件夹

python - 如何对相同 bool 值的 block 进行分组?

python - 如何在用python编写的解释器中实现多重赋值?

python - 查找紧随另一个字符的最常见出现次数