如何获取Python中最新的目录 [英] How to get the newest directory in Python

查看:118
本文介绍了如何获取Python中最新的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种可以找到另一个目录中创建的最新目录的方法
我唯一的方法是 os.listdir()但它显示所有文件和目录。如何仅列出目录,如何访问目录的属性来查找最新创建的目录?
谢谢

I'm looking for a method that can find the newest directory created inside another directory The only method i have is os.listdir() but it shows all files and directories inside. How can I list only directories and how can I access to the attributes of the directory to find out the newest created? Thanks

推荐答案

import os
dirs = [d for d in os.listdir('.') if os.path.isdir(d)]
sorted(dirs, key=lambda x: os.path.getctime(x), reverse=True)[:1]

更新:

可能还有一些解释:

[d for o in os.listdir('。')if os.path.isdir(d )]

是一个列表解析。您可以阅读更多关于他们的信息 here

is a list comprehension. You can read more about them here

代码与

dirs = []
for d in os.listdir('.'):
    if os.path.isdir(d):
        dirs.append(d)

会做,但列表的理解被认为更易读。

would do, but the list comprehension is considered more readable.

是一个内置函数。一些例子是 here

sorted()is a built-in function. Some examples are here

我显示的代码是通过os.path.getctime(ELEMENT)反向排序的dirs内的所有元素。
结果又是一个列表。当然可以使用 [index] 语法和切片

The code I showed sorts all elemens within dirs by os.path.getctime(ELEMENT) in reverse. The result is again a list. Which of course can be accessed using the [index] syntax and slicing

这篇关于如何获取Python中最新的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆