Eli Turasky
Eli Turasky

Reputation: 1061

Change working directory to most recently generated directory

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

Upvotes: 0

Views: 62

Answers (1)

alani
alani

Reputation: 13079

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

Upvotes: 1

Related Questions