Skip to content Skip to sidebar Skip to footer

How To Get The Newest Directory In Python

I'm looking for a method that can find the newest directory created inside another directory The only method i have is os.listdir() but it shows all files and directories inside. H

Solution 1:

import os
dirs = [d for d inos.listdir('.') ifos.path.isdir(d)]
sorted(dirs, key=lambda x: os.path.getctime(x), reverse=True)[:1]

Update:

Maybe some more explanation:

[d for d in os.listdir('.') if os.path.isdir(d)]

is a list comprehension. You can read more about them here

The code does the same as

dirs = []
for d inos.listdir('.'):
    ifos.path.isdir(d):
        dirs.append(d)

would do, but the list comprehension is considered more readable.

sorted()is a built-in function. Some examples are here

The code I showed sorts all elemens within dirs by os.path.getctime(ELEMENT) in reverse. The result is again a list. Which of course can be accessed using the [index] syntax and slicing

Solution 2:

Here's a little function I wrote to return the name of the newest directory:

#!/usr/bin/env pythonimport os
import glob
import operator

deffindNewestDir(directory):
    os.chdir(directory)
    dirs = {}
    fordirin glob.glob('*'):
        if os.path.isdir(dir):
            dirs[dir] = os.path.getctime(dir)

    lister = sorted(dirs.iteritems(), key=operator.itemgetter(1))
    return lister[-1][0]

print"The newest directory is", findNewestDir('/Users/YOURUSERNAME/Sites')

Solution 3:

The following Python code should solve your problem.

import os
import glob
fordirin glob.glob('*'):
  if os.path.isdir(dir):
    printdir,":",os.path.getctime(dir)

Solution 4:

Check out os.walk and the examples in the docs for an easy way to get directories.

root, dirs, files = os.walk('/your/path').next()

Then check out os.path.getctime which depending on your os may be creation or modification time. If you are not already familiar with it, you will also want to read up on os.path.join.

os.path.getctime(path) Return the system’s ctime which, on some systems (like Unix) is the time of the last change, and, on others (like Windows), is the creation time for path.

max((os.path.getctime(os.path.join(root, f)), f) for f in dirs)

Post a Comment for "How To Get The Newest Directory In Python"