2017-02-27 20 views
1

하위 디렉토리가있는 원본 디렉토리의 CAD 도면 (".dwg", ".dxf)을 대상 디렉토리로 복사하고 그 디렉토리를 유지 보수하는 방법을 알아 내려고합니다. 원래 디렉토리 및 하위 폴더 구조Python shutil copytree : 특정 파일 유형을 유지하기 위해 ignore 함수 사용

  • 원래 디렉토리 :. H : \ 탄자니아 ... \ Bagamoyo_Single_line.dwg
  • 소스 디렉토리 : H : \ CAD \ 탄자니아 ... \ Bagamoyo_Single_line.dwg

foll 내에서 @martineau의 다음 답변을 찾았습니다. 때문에 게시물 : Python Factory Function

from fnmatch import fnmatch, filter 
from os.path import isdir, join 
from shutil import copytree 

def include_patterns(*patterns): 
    """Factory function that can be used with copytree() ignore parameter. 

    Arguments define a sequence of glob-style patterns 
    that are used to specify what files to NOT ignore. 
    Creates and returns a function that determines this for each directory 
    in the file hierarchy rooted at the source directory when used with 
    shutil.copytree(). 
    """ 
    def _ignore_patterns(path, names): 
     keep = set(name for pattern in patterns 
          for name in filter(names, pattern)) 
     ignore = set(name for name in names 
         if name not in keep and not isdir(join(path, name))) 
     return ignore 
    return _ignore_patterns 

# sample usage 

copytree(src_directory, dst_directory, 
     ignore=include_patterns('*.dwg', '*.dxf')) 

업데이트 : 18시 21분. 내가

+0

는 그 코드가 이미 그것을 수행하는 방법을 시연한다. 패턴을'include_patterns'에 건네 주면 리턴은'copytree'에 넘겨주는 콜백입니다. 'copytree '는 트리를 가로지를 때 생성 된'_ignore_patterns' 함수에 경로와 이름을 전달하는 작업을합니다. – ShadowRanger

+0

안녕하세요 @ ShadowRanger 이제 다음 작동 방식을 이해합니다. 빈 디렉토리로 끝나지 않도록 include_patterns를 기반으로하는 일치가있는 경우에만 트리를 복사하려면 다음을 수정해야합니다. –

답변

6

shutil 이미 기능 ignore_pattern가 포함 된 include_patterns에게 ('.DWG', ' .DXF')를 포함하지 않는 폴더를 무시하고 싶은 것을 제외하고 다음 코드는 당신이 그렇게 돈, 기대 작품으로 너 자신을 제공해야 해. 스트레이트 documentation에서 :

from shutil import copytree, ignore_patterns 

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*')) 

.pyc 파일과 파일 또는 이름이 디렉토리를 제외한 모든 복사합니다은 tmp.

시작은 조금 까다 (엄격하게 necessairy되지 않음) 무슨 설명입니다 계속 : ignore_patterns은 반환 값으로 _ignore_patterns 함수를 반환하고이 함수는 copytree을 매개 변수로 사용하며 copytree은 필요에 따라이 함수를 호출하므로 hav 이 기능을 호출하는 방법을 알고 있거나 신경 쓰는 사람 _ignore_patterns. 단지 불필요한 요철 파일 (예 : *.pyc)이 복사되지 않도록 제외 할 수 있음을 의미합니다. _ignore_patterns 함수의 이름이 밑줄로 시작한다는 사실은이 함수가 무시할 수있는 구현 세부 사항이라는 힌트입니다.

copytree은 아직 destination 폴더가 존재하지 않을 것으로 예상합니다. copytree이 작동하기 시작하면이 폴더와 하위 폴더가 존재하게되는 것은 문제가되지 않습니다. copytree은이를 처리하는 방법을 알고 있습니다.

이제 include_patterns은 그 반대를하기 위해 작성되었습니다. 명시 적으로 포함되지 않은 모든 것을 무시하십시오. 이 후드 아래 함수를 반환, 당신은 그냥 전화하고, coptytree 그 기능을 무엇을 알고 : :하지만이 같은 방식으로 작동

copytree(source, destination, ignore=include_patterns('*.dwg', '*.dxf')) 
+0

안녕하세요 @Jan, 다음 함수는 보관하려는 파일, 즉 CAD ("* .dwg", "* .dxf")을 기반으로 동적 무시 목록을 생성하므로 다른 모든 파일 형식은 무시됩니다. 나는 다음과 같은 작업을하고 있는데, 내 마지막 장벽은 include_patterns ("* .dwg", "* .dxf")를 기반으로 파일이없는 폴더를 제외시키는 것이다. –

+0

include_patterns 메서드는 어디에 정의되어 있습니까? – AK47

+0

@ AK47 include_patterns는 OP에 정의되어 있습니다. – Jan