【问题标题】:Get a sorted list of folders based on modification date根据修改日期获取排序的文件夹列表
【发布时间】:2014-05-19 13:16:28
【问题描述】:

我正在尝试弄清楚如何将 Python 函数应用于父目录中最旧的 50% 的子文件夹。

例如,如果我在名为 foo 的目录中有 12 个文件夹,我想按修改日期对它们进行排序,然后删除最旧的 6 个。我应该如何处理?

【问题讨论】:

  • “which are most of the most of (not of the old)”到底是什么意思?
  • @jonrsharpe 我的意思是说,在 12 个文件中,我想对其中 6 个修改日期最早的文件做一些事情,而不是在这 6 个文件中的 50% 上。
  • 啊,我明白了 - 我已经改变了措辞(我希望!)让这个更清楚
  • @jonrsharpe 谢谢。现在好多了。

标签: python file datetime directory stat


【解决方案1】:

这样的?

import os
dirpath='/path/to/run/'
dirs = [s for s in os.listdir(dirpath) if os.path.isdir(os.path.join(dirpath, s))]
dirs.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)), reverse=True)

for dir_idx in range(0,len(dirs)/2):
    do_something(dirs[dir_idx])

【讨论】:

  • 正是这个!谢谢。
猜你喜欢
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
相关资源
最近更新 更多