2011-08-23 29 views

答えて

43

深さが固定されている場合は、globは良いアイデアです:

import glob,os.path 
filesDepth3 = glob.glob('*/*/*') 
dirsDepth3 = filter(lambda f: os.path.isdir(f), filesDepth3) 

そうでなければ、それはos.walkを使うにはあまりにも難しいことではありません。

import os,string 
path = '.' 
path = os.path.normpath(path) 
res = [] 
for root,dirs,files in os.walk(path, topdown=True): 
    depth = root[len(path) + len(os.path.sep):].count(os.path.sep) 
    if depth == 2: 
     # We're currently two directories in, so all subdirs have depth 3 
     res += [os.path.join(root, d) for d in dirs] 
     dirs[:] = [] # Don't recurse any deeper 
print(res) 
+0

グロブを使った最初の例は素晴らしく、私はそのトラックに行ったことはありません。感謝万円! – StefanE

3

これはまさにきちんとではありませんUNIXのようなOSの場合は、 "find"のようなシステムツールを利用し、それを外部プログラムとして実行することもできます。

from subprocess import call 
call(["find", "-maxdepth", "2", "-type", "d"]) 

出力を何らかの文字列変数にリダイレクトして、後で処理することができます。

+0

これは深さ1と2のディレクトリを返します。深さ2のディレクトリだけを取得するには、 '' -mindepth ''、 '2' 'を呼び出しパラメータリストに追加する必要があります。 –

+3

'call(" find -maxdepth 2 -mindepth 2 -type d "、shell = True)'を実行することもできます。 – hatmatrix

2

私は本当にphihagの答えが好きです。私は自分のニーズに合わせてそれを適応させました。

def fileNamesRetrieve(top, maxDepth, fnMask ): 
    for d in range(1, maxDepth+1): 
     maxGlob = "/".join("*" * d) 
     topGlob = os.path.join(top, maxGlob) 
     allFiles = glob.glob(topGlob) 
     if fnmatch.fnmatch(os.path.basename(f), fnMask): 
      yield f 

批判歓迎:

import fnmatch,glob 
def fileNamesRetrieve(top, maxDepth, fnMask ): 
    someFiles = [] 
    for d in range(1, maxDepth+1): 
     maxGlob = "/".join("*" * d) 
     topGlob = os.path.join(top, maxGlob) 
     allFiles = glob.glob(topGlob) 
     someFiles.extend([ f for f in allFiles if fnmatch.fnmatch(os.path.basename(f), fnMask) ]) 
    return someFiles 

私はまた、このようなもので発電させることができると思います。

関連する問題