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将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
