How to get the newest directory in Python(如何在 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()
是一个内置函数.一些例子是这里
我展示的代码通过 os.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 中获取最新目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中获取最新目录


基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01