하위 디렉토리가있는 원본 디렉토리의 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분. 내가
는 그 코드가 이미 그것을 수행하는 방법을 시연한다. 패턴을'include_patterns'에 건네 주면 리턴은'copytree'에 넘겨주는 콜백입니다. 'copytree '는 트리를 가로지를 때 생성 된'_ignore_patterns' 함수에 경로와 이름을 전달하는 작업을합니다. – ShadowRanger
안녕하세요 @ ShadowRanger 이제 다음 작동 방식을 이해합니다. 빈 디렉토리로 끝나지 않도록 include_patterns를 기반으로하는 일치가있는 경우에만 트리를 복사하려면 다음을 수정해야합니다. –