python - 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”的所有目录,但我想先根据上次修改的内容对其进行迭代,任何人都可以帮助我。
解决方案
这将构建 (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)))
推荐阅读
- sql - Adding a surrogate key to existing table (SQL SERVER)
- python - Lattice su(2) gauge theory and random number generation in python
- r - R H2O h2o.mojo_predict_df gives odd return inside a function
- python - Numba 优化功能没有速度增益
- python - Python-按属性将类的实例组合在一起
- machine-learning - PAC 学习中的大 O 表示法
- html - Wordpress 中的图像和文本故障
- ruby-on-rails - * 2018 rails: nil:NilClass 的未定义方法“each”
- java - Android Room DAO 如何在单个事务中运行多个 DAO 方法?
- javascript - 如何在文本区域框中下推一行文本?