Search code examples
pythonfiledatetimedirectorystat

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?


Solution

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