Python 基于时间的目录列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4500564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Directory Listing based on time
提问by vkris
How to list the files in a directory based on timestamp?
如何根据时间戳列出目录中的文件?
os.listdir()
lists in arbitrary order.
以任意顺序列出。
Is there a build-in function to list based on timestamp? or by any order?
是否有基于时间戳列出的内置函数?或按任何顺序?
采纳答案by HarryM
You could call stat()on each of the files and sort by one of the timestamps, perhaps by using a key function that returns a file's timestamp.
您可以调用stat()每个文件并按其中一个时间戳排序,也许可以使用返回文件时间戳的键函数。
import os
def sorted_ls(path):
mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
return list(sorted(os.listdir(path), key=mtime))
print(sorted_ls('documents'))
回答by vkris
My immediate solution is,
我的直接解决方案是,
>>> import commands
>>> a = commands.getstatusoutput("ls -ltr | awk '{print }'")
>>> list =a[1].split('\n')
As per the duplicate post pointed by bluish, this is a bad solution; why is it bad?
根据 blueish 指出的重复帖子,这是一个糟糕的解决方案;为什么不好?

