I am trying to figure out how to apply a Python function to the oldest 50% of the sub-folders inside my parent directory.
For instance, if I have 12 folders inside a directory called foo
, I'd like to sort them by modification date and then remove the oldest 6. How should I approach this?
In any version of Windows, when you sort items in a folder in descending order by Date Modified column, folders move to the bottom and files go to the top. What many users may want is folders to be sorted separately and remain at the top, and files below. The following is the usual behavior.
How to sort files by modification date in Python. You can use sorted () to sort the files, and use key=lambda t: os.stat (t).st_mtime to sort by modification time. This will sort with ascending modification time (i.e. most recently modified file last).
List Files Based on Modification Time The below command lists files in long listing format, and sorts files based on modification time, newest first. To sort in reverse order, use '-r' switch with this command.
Listing of files in directory based on last modification time of file’s status information, or the 'ctime'. This command would list that file first whose any status information like: owner, group, permissions, size etc has been recently changed.
Something like this?
import os
dirpath='/path/to/run/'
dirs = [s for s in os.listdir(dirpath) if os.path.isdir(os.path.join(dirpath, s))]
dirs.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)), reverse=True)
for dir_idx in range(0,len(dirs)/2):
do_something(dirs[dir_idx])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With