2

ディレクトリ内の最新のファイルと2番目に新しいファイルを識別しようとしています。これは私が使用するつもりだったコードです:

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

誰か考えがありますか?

4

2 に答える 2

7

os.listdir相対名を返すのでos.path.join、それらを絶対にするために使用する必要があります。

allConfigs = sorted(os.listdir(CONFIGS),
    key=lambda p: os.path.getctime(os.path.join(CONFIGS, p))
于 2012-10-03T19:18:41.707 に答える
1

閉じ括弧が欠落していると思います:

allConfigs = sorted(os.listdir(CONFIGS),
   key=lambda p: os.path.getctime(os.path.join(CONFIGS, p)))
于 2013-02-19T07:26:01.610 に答える