How to get the newest directory in Python
directory, operating-system, python
Solution
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
Problem
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