首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试识别目录中的最新文件和第二个最新文件

尝试识别目录中的最新文件和第二个最新文件
EN

Stack Overflow用户
提问于 2012-10-04 03:17:38
回答 2查看 1.4K关注 0票数 2

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

代码语言:javascript
复制
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])

我遇到了这个错误,我不知道为什么:

代码语言:javascript
复制
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'
>>>

有人有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-04 03:18:42

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

代码语言:javascript
复制
allConfigs = sorted(os.listdir(CONFIGS),
    key=lambda p: os.path.getctime(os.path.join(CONFIGS, p))
票数 7
EN

Stack Overflow用户

发布于 2013-02-19 15:26:02

我认为它缺少右括号:

代码语言:javascript
复制
allConfigs = sorted(os.listdir(CONFIGS),
   key=lambda p: os.path.getctime(os.path.join(CONFIGS, p)))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12715309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档