Sometimes, we want to get a directory listing sorted by creation date in Python.
In this article, we’ll look at how to get a directory listing sorted by creation date in Python.
How to get a directory listing sorted by creation date in Python?
To get a directory listing sorted by creation date in Python, we can use the glob
function.
For instance, we write
import glob
import os
search_dir = "/mydir/"
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))
to get the files in the search_dir
with glob.glob
.
And we call filter
to return an iterable with the glob
results that are files with os.path.isfile
.
Next, we convert the iterable to a list with list
.
Then we sort the list by creation date by calling sort
with the key
argument set to a function that gets the modified date with os.path.getmtime(x)
and sort by the returned value.
Conclusion
To get a directory listing sorted by creation date in Python, we can use the glob
function.