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 中获取最新目录
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 沿轴计算直方图 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
