2014-11-06 3 views
4

GNU findfind . -type d -empty -delete과 마찬가지로 빈 서브 디렉토리 (emtpy 서브 디렉토리 등을 포함하는 서브 디렉토리)를 포함하는 빈 디렉토리를 찾고 싶습니다. 그러나을 삭제하지 않고 을 삭제하지 마십시오. 기존 솔루션이 있습니까? 아니면 수동으로 os.walk을 사용해야합니까? (아마도 topdown=False을 사용하고 지금까지 발견 된 빈 하위 디렉토리를 추적해야합니까?)Python에서 재귀 적으로 빈 디렉토리를 찾는 방법은 무엇입니까?

+0

import os def recursive_delete_if_empty(path): """Recursively delete empty directories; return True if everything was deleted.""" if not os.path.isdir(path): # If you also want to delete some files like desktop.ini, check # for that here, and return True if you delete them. return False # Note that the list comprehension here is necessary, a # generator expression would shortcut and we don't want that! if all([recursive_delete_if_empty(os.path.join(path, filename)) for filename in os.listdir(path)]): # Either there was nothing here or it was all deleted os.rmdir(path) return True else: return False 
'Popen' +'내가 유닉스에서 실행해야했다 find' 경우/리눅스 –

+0

@ SergeBallesta 전자의 가장 좋은 추측은 지금까지도. 그래도 라이브러리 함수가 없는지 궁금 해서요 ... 아니면 'find'모듈 일 수도 있습니다. 그것은 많은 것들을 단순화 할 수 있습니다. –

+0

@SergeBallesta ['os.walk'을 사용하여 구현했습니다.] (http://stackoverflow.com/a/26775425/321973), 충분히 Pythonic이 되길 바랍니다. –

답변

2

좋아, 여기 내 수동 해결책은 os.walk입니다. 물론 is_empty 기능을 수정할 수 있습니다. 숨겨진 파일을 제외하거나, 내 예를 desktop.ini에하기 : 여기

import os 


def empty_dirs(root_dir='.', recursive=True): 
    empty_dirs = [] 
    for root, dirs, files in os.walk(root_dir, topdown=False): 
     #print root, dirs, files 
     if recursive: 
      all_subs_empty = True # until proven otherwise 
      for sub in dirs: 
       full_sub = os.path.join(root, sub) 
       if full_sub not in empty_dirs: 
        #print full_sub, "not empty" 
        all_subs_empty = False 
        break 
     else: 
      all_subs_empty = (len(dirs) == 0) 
     if all_subs_empty and is_empty(files): 
      empty_dirs.append(root) 
      yield root 


def is_empty(files): 
    return (len(files) == 0 or files == ['desktop.ini']) 


def find_empty_dirs(root_dir='.', recursive=True): 
    return list(empty_dirs(root_dir, recursive)) 


print find_empty_dirs(recursive=False) 
6

하는 발전기와 os.walk 사용하여 간단한 솔루션입니다 :

import os 

def find_empty_dirs(root_dir='.'): 
    for dirpath, dirs, files in os.walk(root_dir): 
     if not dirs and not files: 
      yield dirpath 

print list(find_empty_dirs()) 

topdown=False이 필요한 이유가 표시되지 않습니다를, 난 몰라 그것이 무엇이든 변화한다고 생각하십시오.

빈 디렉터리 만 포함하는 디렉터리는 비어 있지 않은 것으로 간주하지만 이후 find . -type d -empty도 마찬가지입니다.

더 많은 테스트를 통해 find . -type d -empty -delete을 참조하십시오. 빈 서브 디렉토리를 먼저 삭제 한 다음 상위 디렉토리를 삭제하십시오. 하지만 os.walk를 사용하면 내림차순으로 하위 디렉토리 목록을 읽으므로 topdown=False으로도 작동하지 않습니다.

빈 하위 디렉토리 나무가 될 수 삭제 재귀 솔루션 :

나는`os.walk`을 사용하려고, 또는 것
+0

호기심 - 아, 나는 질문에서 내 실수를 본다. '찾는다. 'd -empty'는'-delete'를 사용할 때만 재귀 적으로 작동합니다. 나는 내 질문을 고쳐야 할까봐 두려워, 귀하의 의견을 인정하지만, 발전기 어느 쪽이든 좋네요 소리가 –

+0

나는 [내 대답] (http://stackoverflow.com/a/26775425/321973)을 포함하도록 수정 생성기를 사용하지만, 지금까지 나는 지금까지 발견 된 모든 빈 서브 디렉토리를 저장해야하는데, 그래서'topdown = False'가 필요합니다. 그러나 아마도 쉬운 방법 일 수 있습니다. –