Search code examples
pythonfilepathpython-os

How to get the latest folder in a directory using Python


I need to retrieve the directory of the most recently create folder. I am using a program that will output a new run## folder each time it is executed (i.e run01, run02, run03 and so on). Within any one run## folder resides a data file that I want analyze (file-i-want.txt).

folder_numb = 'run01'
dir = os.path.dirname(__file__)
filepath = os.path.join(dir, '..\data\directory',run_numb,'file-i-want.txt')

In short I want to skip having to hardcode in run## and just get the directory of a file within the most recently created run## folder.


Solution

  • You can get the creation date with os.stat

    path = '/a/b/c'
    
    #newest
    
    newest = max([f for f in os.listdir(path)], key=lambda x: os.stat(os.path.join(path,x)).st_birthtime)
    
    # all files sorted
    
    sorted_files = sorted([f for f in os.listdir(path)],key=lambda x: os.stat(os.path.join(path, x)).st_birthtime, reverse=True)