python - 在根路径中获取最新目录

标签 python

我想在根目录中找到最新的目录:

目前此代码在根路径中查找所有目录,还查找修改后的时间:

import os
from datetime import datetime

root = r'D:\drivers'

def totimeformat(tm):
    return tm.strftime('%Y-%m-%d %H:%M:%S')

dirs = []
for dir in directories:
    d = os.path.join(root, dir)
    if os.path.isdir(d):
        print(d + '' + totimeformat(datetime.fromtimestamp(os.path.getatime(d))))
        dirs.append(d)

最佳答案

您的代码基本上是好的。您只需更改它以反射(reflect)您描述的逻辑:

import os
from datetime import datetime

root = r'D:\drivers'

def totimeformat(tm):
    return tm.strftime('%Y-%m-%d %H:%M:%S')

dirs = []
newestdir = None
newesttime = 0
for dir in directories:
    d = os.path.join(root, dir)
    if os.path.isdir(d):
        t = os.path.getatime(d)
        if t > newesttime:
            newestdir = d
            newesttime = t
print(newestdir + '' + totimeformat(datetime.fromtimestamp(newesttime)))

关于python - 在根路径中获取最新目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55502832/

相关文章:

python - pandas DataFrame - 查找偏移列之间的最大值

python - 使用 Python 在迭代创建的嵌套列表中选择上面的级别

python - 在 MySQL + Python 中使用 AND 运算符参数化子字符串查询的安全方法

python - 如何更改 numpy recarray 某些列的数据类型?

python - 获取wav文件的采样率而不加载整个文件

python - 如何使用 'm/d/yy' 格式修剪时间戳中的空格

python - 是否有任何使用 TensorFlow 实现的异常检测算法的示例?

python - 从 crontab 执行 Python 程序

python - pd.get_dummies 与在 statsmodel ols 中简单包含分类变量相同吗?

python - 模块导入时出现属性错误 - 在某些计算机上有效