基于时间的目录列表

发布于 2024-10-08 07:45:50 字数 114 浏览 0 评论 0原文

如何根据时间戳列出目录中的文件?

 os.listdir() 

以任意顺序列出。

是否有内置函数可以根据时间戳列出?或按任何命令?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哥,最终变帅啦 2024-10-15 07:45:50

您可以对每个文件调用 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'))

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'))
绝不放开 2024-10-15 07:45:50

我的直接解决方案是,

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

根据 blueish 指出的重复帖子,这是一个糟糕的解决方案;为什么不好?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文