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$ 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'
>>>

有人有什么想法吗?

最佳答案

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

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

关于python - 试图识别目录中最新和第二新的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715309/

相关文章:

python - 带有休克数据的 Multiprocessing.Queue 导致 _wait_for_tstate_lock

python - 从python cgi执行用户shell命令

python - 修改 Damerau-Levenshtein 算法以跟踪转换(插入、删除等)

python - 如何丢弃图像中重叠的矩形?

python - pandas:来自 groupby.value_counts() 的字典

python - 在 Django 中检索通用外键关系的 'many' 结尾

python - 查找标识符的值

python - 如何关闭 QDialog

python - 我应该如何正确使用Selenium

python - GoTo(基本)程序