4

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

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
nam
  • 3,542
  • 9
  • 46
  • 68

4 Answers4

9
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

Community
  • 1
  • 1
mfussenegger
  • 3,931
  • 23
  • 18
  • Can I use listdir() instead of listdir('.')? – nam Jun 12 '12 at 07:23
  • No, os.listdir takes a mandatory argument. The '.' is just a shortcut for "current directory" (You could also use os.curdir instead, or of course, pass the absolute/relative path to the directory you're interested in) – mfussenegger Jun 12 '12 at 07:31
  • 'sorted(dirs, key=lambda x: os.path.getctime(x), reverse=True)[:1]' actually show a list right, so I can get just the first element by 'sorted(dirs, key=lambda x: os.path.getctime(x), reverse=True)[0]' ? – nam Jun 12 '12 at 07:58
  • 1
    @HOAINAMNGUYEN I updated the answer. I hope that now it is more clear to you what the code does. – mfussenegger Jun 12 '12 at 10:55
  • how to give user defined path here ? – Shashank Oct 28 '21 at 14:20
7

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')
jshawl
  • 3,315
  • 2
  • 22
  • 34
  • Can you explain the line lister = sorted(dirs.iteritems(), key=operator.itemgetter(1)) ? – nam Jun 11 '12 at 16:34
  • Sure! So basically, I'm just creating a dictionary where the key is the name of the directory, and the value is the creation time of the directory. Then, I sort the dictionary based on the values to find the newest directory. Also, check out http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value#answer-613218 – jshawl Jun 11 '12 at 16:38
  • sorted() is a built-in function. Googling for "python sorted" gets you the the docs and a few other SO questions. http://docs.python.org/library/functions.html#sorted – istruble Jun 11 '12 at 16:45
5

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)
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
jshawl
  • 3,315
  • 2
  • 22
  • 34
  • 1
    Does this find the newest one? – JoeFish Jun 11 '12 at 16:31
  • @jessh Your other answer is basically a duplicate of this answer with sorting added. It is best to edit your existing answers if you are just improving them. – istruble Jun 11 '12 at 16:41
  • Thanks! but the OP's question was how to find atributes of the directories (creation time), with the eventual intent of sorting them. Thus I answered his question. The second answer goes a step further to sort. I would prefer to keep them separate – jshawl Jun 11 '12 at 16:47
  • 1
    I guess I'm just confused how this solves the problem when the first line of the problem is `I'm looking for a method that can find the newest directory created inside another directory`. – JoeFish Jun 11 '12 at 16:54
  • The op's question is exactly: "How can I list only directories and how can I access to the attributes of the directory to find out the newest created?" – jshawl Jun 11 '12 at 16:59
0

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)
istruble
  • 13,363
  • 2
  • 47
  • 52