To sort files by date using Python, you can use the os module listdir() function to get all files in a directory. Then use the
os.path.getcttime() or os.path.getmttime() to get the file creation or modification dates, respectively, inside a sort function.
import os
files = os.listdir()
print(files)
files.sort(key=lambda x: os.path.getmtime(x)) #Sort by Modification Time
print(files)
#Output
['code1.txt', 'code2.txt', 'code3.txt']
['code1.txt', 'code3.txt', 'code2.txt']
When working with files in Python, the ability to get a list of files in a directory and sort by date can be useful.
With the help of the Python os module, we can easily get a list of files and sort them by either creation date or modification date.
The Python os module has many great functions which help us interact with the operating system of our computer.
Let’s say we have the following directory with three files.
To get the files in this directory, we first use the os module listdir() function. Then, we have two options for sorting; we can sort by file modification date or by file creation date.
How to Sort Files by File Modification Date with Python
If you want to sort files by file modification date, the easiest way is to sort using a lambda function and use the os.path.os.path.getmtime() function.
Below shows you how you would sort files by modification date in Python for our example directory.
import os
files = os.listdir()
print(files)
files.sort(key=lambda x: os.path.getmtime(x)) #Sort by Modification Time
print(files)
#Output
['code1.txt', 'code2.txt', 'code3.txt']
['code1.txt', 'code3.txt', 'code2.txt']
How to Sort Files by File Creation Date with Python
If you want to sort files by file creation date, the easiest way is to sort using a lambda function and use the os.path.os.path.getctime() function.
Below shows you how you would sort files by creation date in Python for our example directory.
import os
files = os.listdir()
print(files)
files.sort(key=lambda x: os.path.getctime(x)) #Sort by Creation Time
print(files)
#Output
['code1.txt', 'code2.txt', 'code3.txt']
['code1.txt', 'code2.txt', 'code3.txt']
Hopefully this article has been useful for you to learn how to sort files by date in Python.