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

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

问题描述

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

解决方案

import osdirs = [d for d in os.listdir('.') if os.path.isdir(d)]排序(目录,键=lambda x:os.path.getctime(x),反向=真)[:1]

更新:

也许更多解释:

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

是一个列表推导.您可以在这里

代码的作用与

dirs = []对于 os.listdir('.') 中的 d:如果 os.path.isdir(d):dirs.append(d)

可以,但列表推导被认为更具可读性.

sorted()是一个内置函数.一些例子是这里

我展示的代码通过 o​​s.path.getctime(ELEMENT) 对 dirs 中的所有元素进行反向排序.结果又是一个列表.当然可以使用 [index] 语法和 切片

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]

Update:

Maybe some more explanation:

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

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

The code does the same as

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

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

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

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天全站免登陆