获取目录中所有文件列表的最佳方法是什么,按日期排序 [创建 |修改],使用python,在windows机器上?
原文由 Liza 发布,翻译遵循 CC BY-SA 4.0 许可协议
我过去曾为 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))
原文由 Jay 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答861 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
_更新_:在 Python 3 中按修改日期对
dirpath
的条目进行排序:(将 @Pygirl 的回答 放在这里以获得更大的知名度)
如果您已经有了文件名列表
files
,然后在 Windows 上按创建时间对其进行排序(确保该列表包含绝对路径):您可以获得的文件列表,例如,使用
glob
如@Jay 的回答 所示。旧答案这是
@Greg Hewgill
的答案 的更详细版本。是最符合题目要求的。它区分创建日期和修改日期(至少在 Windows 上)。例子: