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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
stratis
  • 7,750
  • 13
  • 53
  • 94

1 Answers1

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])
woot
  • 7,406
  • 2
  • 36
  • 55