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!

4

1 回答 1

0

您可以使用函数和理解列表来阐明列出文件的过程os.path.isfile(),但这取决于您。如果您查看评论中的相关链接,您会看到该os.path.getctime()函数,它允许您获取 Windows 系统中文件的创建时间和类 Unix 系统中的最后修改时间(如stat()系统调用st_mtime属性):

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: os.path.getctime(x))

但到目前为止,您的代码看起来是正确的。如果您提供解释器抛出的错误或完整的代码,也许我们会更有帮助。

于 2013-08-30T03:24:11.080 回答