nam
nam

Reputation: 3632

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. How can I list only directories and how can I access to the attributes of the directory to find out the newest created? Thanks

Upvotes: 4

Views: 9424

Answers (4)

mfussenegger
mfussenegger

Reputation: 3971

import os
dirs = [d for d in os.listdir('.') if os.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 in os.listdir('.'):
    if os.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

Upvotes: 9

istruble
istruble

Reputation: 13702

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)

Upvotes: 0

jshawl
jshawl

Reputation: 3483

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

#!/usr/bin/env python

import os
import glob
import operator

def findNewestDir(directory):
    os.chdir(directory)
    dirs = {}
    for dir in 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')

Upvotes: 7

jshawl
jshawl

Reputation: 3483

The following Python code should solve your problem.

import os
import glob
for dir in glob.glob('*'):
  if os.path.isdir(dir):
    print dir,":",os.path.getctime(dir)

Upvotes: 5

Related Questions