2017-11-24 7 views
0

私はbase_pathの下にサブディレクトリ 'f'を持っています。 私のpython Skriptは、 "base_path"の下に5つのディレクトリを作成しています。このような例( 'a'、 'b'、 'c'、 'd'、 'e')。だから私はbase_pathの下に古いディレクトリ( 'f')と5つの新しいディレクトリ( 'a'、 'b'、 'c'、 'd'、 'e')の下にあります。 私は新しい上場:LinuxでPython 2.7を使って作成した日付と同じ順序でサブディレクトリをリストする方法は?

os.chdir(base_path) 

for i in range (5): 
    dirs = [os.path.join(os.getcwd(),d) for d in os.listdir(os.getcwd()) if ((os.path.isdir(d)) and 'f' not in d)] 

    print dirs 

私は

['e', 'a', 'b', 'c', 'd'] 

のようなリストを持っているが、私はすべての新しい作成したディレクトリを追加機能を持つようにしたい:同じで

[ 'a', 'b', 'c', 'd', 'e'] 

彼らの創造日の順序。

注:4つのディレクトリで動作しましたが、5つのディレクトリ番号があります。

+0

は 'ソート(os.listdir(os.getcwd(と' 'os.listdir(os.getcwdを())交換してみてください))、key = lambda x:os.path.getmtime(os.path.join(os.getcwd()、x))) ' –

+0

ありがとうございました! – Salem

答えて

0

返されたファイルをos.listdir()でソートする必要があります。これは、次のように各ファイルに対してos.path.getmtime()によって返された値にソートすることによって行うことができます。

os.chdir(base_path) 

for i in range (5): 
    dirs = [os.path.join(os.getcwd(),d) for d in sorted(os.listdir(os.getcwd()), key=lambda x: os.path.getmtime(os.path.join(os.getcwd(), x))) if ((os.path.isdir(d)) and 'f' not in d)] 

    print dirs 
+0

ありがとうございました:)それは役に立ちました! – Salem

関連する問題