首页 > 解决方案 > Python:根据修改时间对目录下的目录进行排序

问题描述

我想根据修改时间迭代目录,

在此路径“C:\Users\smith\AppData\Local\Temp”下,我有许多同名目录“scoped_dir”现在我想访问最新的“scoped_dir”,

import os
import time
import glob
file_path = 'C:/Users/smith/AppData/Local/Temp'
for root, dir, files in os.walk(file_path, topdown=True):
 if 'scoped_dir' in root:
    print("root :" + str(root))
    print("dir :" + str(dir))
    print("files :" + str(files))

使用上面提到的代码,我可以访问名称为“scoped_dir”的所有目录,但我想先根据上次修改的内容对其进行迭代,任何人都可以帮助我。

标签: python

解决方案


这将构建 (dir, modify_time) 元组的列表。然后以修改时间的相反顺序对列表进行排序,并以某种可读格式作为演示打印。但是要小心,如果 'scoped_dir' 恰好是目录的子字符串,它也会被包含在内,所以理论上你可能会得到比你需要的更多的目录。

import glob, os, time

dirs = []
for root, dir, files in os.walk(file_path):
    if 'scoped_dir' in root:
        dirs.append((root, os.path.getmtime(root)))

dirs = sorted(dirs, key=lambda x: x[1], reverse=True)

for dir, tm in dirs:  # iteration based on last modified first
    print(dir, time.strftime('%d-%m-%Y %H:%M', time.gmtime(tm)))
  

推荐阅读