[英]Trying to identify the newest and second newest file in a directory
我試圖識別目錄中的最新和第二個最新文件。 這是我打算使用的代碼:
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))
我認為它缺少結束括號:
allConfigs = sorted(os.listdir(CONFIGS),
key=lambda p: os.path.getctime(os.path.join(CONFIGS, p)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.