Home >Backend Development >Python Tutorial >How to Sort a Directory Listing by Creation Date in Python?
Getting a Directory Listing Sorted by Creation Date in Python
When working with directories in Python, it may be necessary to retrieve a listing of files sorted by their creation dates. To accomplish this task, the following approach can be employed:
import os import glob # For more flexible directory filtering
Use os.listdir() or glob.glob() to obtain a list of all file paths in the desired directory.
search_dir = "/mydir/" files = os.listdir(search_dir) # Or use glob for more advanced filtering files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
If you only need files in your list, apply a filter to remove any directories or symlinks present in the list.
files = list(filter(os.path.isfile, files))
Utilize the key=lambda x: os.path.getmtime(x) argument in the sort function to sort files based on their last modification times, which are an approximation of their creation dates.
files.sort(key=lambda x: os.path.getmtime(x))
For some functions that require full file paths, such as os.path.getmtime(), it may be necessary to append the original directory path to each file in the list.
files = [os.path.join(search_dir, f) for f in files]
The above is the detailed content of How to Sort a Directory Listing by Creation Date in Python?. For more information, please follow other related articles on the PHP Chinese website!