Python 正在尝试标识目录中的最新和第二个最新文件

Python 正在尝试标识目录中的最新和第二个最新文件,python,Python,我试图识别目录中最新和第二新的文件。这是我打算使用的代码: CONFIGS = "/Users/root/dev/config-files/" allConfigs = sorted(os.listdir(CONFIGS), key=os.path.getctime) t1 = "%s/%s" % (CONFIGS, allConfigs[-1]) t2 = "%s/%s" % (CONFIGS, allConfigs[-2]) 我遇到了这个错误,我不知道为什么: MBA:dev root$

我试图识别目录中最新和第二新的文件。这是我打算使用的代码:

CONFIGS = "/Users/root/dev/config-files/"
allConfigs = sorted(os.listdir(CONFIGS), key=os.path.getctime)
t1 = "%s/%s" % (CONFIGS, allConfigs[-1])
t2 = "%s/%s" % (CONFIGS, allConfigs[-2])
我遇到了这个错误,我不知道为什么:

MBA:dev root$ python
Python 2.7.3 (default, Apr 19 2012, 00:55:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> CONFIGS = "/Users/root/dev/config-files/"
>>> allConfigs = sorted(os.listdir(CONFIGS), key=os.path.getctime)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 64, in getctime
    return os.stat(filename).st_ctime
OSError: [Errno 2] No such file or directory: 'newest.txt'
>>>
MBA:devroot$python
Python 2.7.3(默认值,2012年4月19日00:55:09)
[GCC 4.2.1(基于苹果公司5658版本)(LLVM版本2335.15.00)]关于达尔文
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>导入操作系统
>>>CONFIGS=“/Users/root/dev/config files/”
>>>allConfigs=sorted(os.listdir(CONFIGS),key=os.path.getctime)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
getctime中的文件“/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py”,第64行
返回os.stat(filename).st\u-ctime
OSError:[Errno 2]没有这样的文件或目录:“最新的.txt”
>>>

有人有什么想法吗?

os.listdir
返回相对名称,因此您必须使用
os.path.join
使其成为绝对名称:

allConfigs = sorted(os.listdir(CONFIGS),
    key=lambda p: os.path.getctime(os.path.join(CONFIGS, p))

我认为它缺少结束括号:

allConfigs = sorted(os.listdir(CONFIGS),
   key=lambda p: os.path.getctime(os.path.join(CONFIGS, p)))
我没有想到这一点。(现在看来很明显)。谢谢你,玛蒂恩!