Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a sorted list of folders based on modification date

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?

like image 792
stratis Avatar asked May 19 '14 13:05

stratis


People also ask

How do I sort items in a folder by date modified?

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 do I sort a file by modification date in Python?

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).

How to sort files based on modification time in Linux?

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.

How to list files in directory based on last modification time?

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.


1 Answers

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])
like image 149
woot Avatar answered Oct 31 '22 11:10

woot