How to get a directory listing sorted by creation date in Python?

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 pathlib module.

For instance, we write:

import os
from pathlib import Path

dirpath = '/'
paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)
print(paths)

We get the directories within dirpath with Path(dirpath).iterdir().

And we call sorted with Path(dirpath).iterdir() and key to os.path.getmtime sort by time modified.

Finally, we assign the returned list of path objects to paths.

Therefore, paths is something like:

[PosixPath('/boot'), PosixPath('/media'), PosixPath('/srv'), PosixPath('/lib64'), PosixPath('/var'), PosixPath('/home'), PosixPath('/root'), PosixPath('/sbin'), PosixPath('/lib32'), PosixPath('/gocode'), PosixPath('/run_dir'), PosixPath('/phase2-erlang.tar.bz2'), PosixPath('/phase2-jest.tar.bz2'), PosixPath('/phase2-d.tar.bz2'), PosixPath('/phase2-mercury.tar.bz2'), PosixPath('/phase2-express.tar.bz2'), PosixPath('/phase2-php.tar.bz2'), PosixPath('/phase2-guile.tar.bz2'), PosixPath('/phase2-csharp.tar.bz2'), PosixPath('/phase2-fortran.tar.bz2'), PosixPath('/phase2-fsharp.tar.bz2'), PosixPath('/phase2-rlang.tar.bz2'), PosixPath('/phase2-cpp.tar.bz2'), PosixPath('/phase2-assembly.tar.bz2'), PosixPath('/phase2-crystal.tar.bz2'), PosixPath('/phase2-pascal.tar.bz2'), PosixPath('/phase2-prolog.tar.bz2'), PosixPath('/phase2-haskell.tar.bz2'), PosixPath('/phase2-clisp.tar.bz2'), PosixPath('/phase2-love2d.tar.bz2'), PosixPath('/phase2-elixir.tar.bz2'), PosixPath('/phase2-cpp11.tar.bz2'), PosixPath('/phase2-react_native.tar.bz2'), PosixPath('/bin'), PosixPath('/lib'), PosixPath('/usr'), PosixPath('/opt'), PosixPath('/mnt'), PosixPath('/inject'), PosixPath('/io'), PosixPath('/etc'), PosixPath('/.dockerenv'), PosixPath('/sys'), PosixPath('/proc'), PosixPath('/dev'), PosixPath('/config'), PosixPath('/nix'), PosixPath('/run'), PosixPath('/tmp')]

Conclusion

To get a directory listing sorted by creation date in Python, we can use the pathlib module.