Directory Listing based on time [duplicate]

有些话、适合烂在心里 提交于 2019-12-17 23:39:34

问题


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?


回答1:


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



回答2:


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?



来源:https://stackoverflow.com/questions/4500564/directory-listing-based-on-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!