2011-08-23 5 views
21

지정된 경로와 고정 된 깊이의 디렉토리 목록을 반환하는 기능을 원한다면 몇 가지 대안을 곧 실현할 수 있습니다. 나는 os.walk을 꽤 많이 사용하고 있지만 깊이를 계산할 때 코드가보기 싫어지기 시작했습니다.Python에서 지정된 깊이의 디렉토리 나열

실제로 가장 "깔끔한"구현은 무엇입니까?

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) 

답변

43

glob 좋은 생각이다 하지만 유닉스 계열 OS에서는 "find"와 같은 시스템 도구를 사용하고 외부 프로그램으로 실행할 수 있습니다. 예를 들면 다음과 같습니다.

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

다음 처리를 위해 출력을 일부 문자열 변수로 리디렉션 할 수 있습니다.

+0

glob를 사용한 첫 번째 예는 훌륭하고 나는 그 트랙을 본 적이 없었습니다. 대단히 감사합니다! – StefanE

3

이 정확히 깔끔한되지 않습니다 : os.walk 사용하기 너무 열심히하지 않아야, 그렇지 않으면

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

:

깊이가 고정되어있는 경우
+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 

가 나는 또한이 같은 뭔가 발전기 만들 수있는 것 같아요.

관련 문제