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?

4
  • What on earth does "which are the oldest (not of the oldest)" mean? Commented May 19, 2014 at 13:18
  • @jonrsharpe 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. Commented May 19, 2014 at 13:21
  • Ah, I see - I have altered the wording to (I hope!) make this clearer Commented May 19, 2014 at 13:22
  • @jonrsharpe Thanks. That's better now. Commented May 19, 2014 at 13:22

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly this! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.