0

I'm trying to find the name of the most recently created file in a directory:

    try:
        #print "creating path"
        os.makedirs(self.path)
        self.dictName = "0"
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise
        listOfFiles = os.listdir(self.path)
        listOfFiles = filter(lambda x: not os.path.isdir(x), listOfFiles)
        print "creating newestDict"
        newestDict = max(listOfFiles, key=lambda x: os.stat(x).st_mtime) ------<
        print "setting self.name"

The arrow points where the code is causing the program to crash. Printing listOfFiles returns a non-empty list. This is using a third-party python program that has its own interpreter. Any ideas what I'm doing wrong? Thanks!

  • 1
    Check this out http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python – moliware Aug 29 '13 at 21:30

1 Answers1

0

You can clarify the process of listing files by using the os.path.isfile() function and a comprehension list, but that is up to you. If you look into the related link in the comments, you'll see the os.path.getctime()function, which allows you to get the creation time of a file in windows systems and the time of the last modification in Unix-like systems (like the stat()system call st_mtime attribute):

from os import listdir
from os.path import isfile, join, getctime

listOfFiles = [f for f in listdir(self.path) if isfile(join(self.path,f))]
newestDict = max(listOfFiles, key=lambda x: getctime(x))

But so far, your code looks correct. Maybe we could be more helpful if you provide the error the interpreter is throwing or the full piece of code.

Community
  • 1
  • 1
Alfageme
  • 2,075
  • 1
  • 23
  • 30