Get a sorted list of folders based on modification date
Asked Answered
L

1

5

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?

Levitation answered 19/5, 2014 at 13:16 Comment(4)
What on earth does "which are the oldest (not of the oldest)" mean?Chelicera
@Chelicera I meant to say that out of the say, 12 files, I want to do something with the 6 of them which have the oldest modification date and not on the 50% of those 6.Levitation
Ah, I see - I have altered the wording to (I hope!) make this clearerChelicera
@Chelicera Thanks. That's better now.Levitation
S
7

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])
Selfcentered answered 19/5, 2014 at 13:29 Comment(1)
Exactly this! Thank you.Levitation

© 2022 - 2024 — McMap. All rights reserved.