开发者

Directory Listing based on time [duplicate]

This question already has answers here: How do you get a directory listing sorted by creation date in python? (19 answers) Closed 9 years ago.

How to list the files in a directory based on timestamp?开发者_如何学JAVA

 os.listdir() 

lists in arbitrary order.

Is there a build-in function to list based on timestamp? or by any order?


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.

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'))


My immediate solution is,

 >>> import commands
 >>> a = commands.getstatusoutput("ls -ltr | awk '{print $9}'")
 >>> list  =a[1].split('\n')

As per the duplicate post pointed by bluish, this is a bad solution; why is it bad?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜