stratis
stratis

Reputation: 8052

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?

Upvotes: 5

Views: 2259

Answers (1)

woot
woot

Reputation: 7616

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

Upvotes: 7

Related Questions