0

Is there a way to change your directory to the most recently generated directory? I am creating a new directory every 12 hours and want to iteratively loop through the most recent x amount of directories.

Something similar to this but for a directory.

How to get the latest file in a folder using python

Eli Turasky
  • 981
  • 2
  • 11
  • 28
  • `glob.glob` will return directory and files so what's wrong ? – Ôrel Oct 07 '20 at 15:50
  • The linked answer should work after modifying the glob expression to return only directories: `list_of_files = glob.glob('/path/to/folder/*/')` – 0x5453 Oct 07 '20 at 15:51

1 Answers1

1

The following should basically work.

import os

parent_dir = "."  # or whatever

paths = [os.path.join(parent_dir, name) for name in os.listdir(parent_dir)]
dirs = [path for path in paths if os.path.isdir(path)]
dirs.sort(key=lambda d: os.stat(d).st_mtime)
os.chdir(dirs[-1])

Note that this will change to the directory with the most recent modification time. This might not be the most recently created directory, if a pre-existing directory was since modified (by creating or deleting something inside it); the information about when a directory is created is not something that is stored anywhere -- unless of course you use a directory naming that reflects the creation time, in which case you could sort based on the name rather than the modification time.

I haven't bothered here to guard against race conditions with something creating/deleting a directory during the short time that this takes to run (which could cause it to raise an exception). To be honest, this is sufficiently unlikely, that if you want to deal with this possibility, it would be sufficient to do:

while True:
    try:
        #all the above commands
        break
    except OSError:
        pass
alani
  • 12,573
  • 2
  • 13
  • 23