CAD図面( ".dwg"、 ".dxf")をサブフォルダを持つソースディレクトリからコピー先ディレクトリにコピーし、元のディレクトリとサブフォルダ構造Python shutil copytree:特定のファイルタイプを維持するためにignore関数を使用する
- 元のディレクトリ:H:\タンザニア... \ Bagamoyo_Single_line.dwg
- ソースディレクトリ:H:\ CAD \タンザニア... \ Bagamoyo_Single_line.dwg
私は@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予想通り、次のコードは、すでに機能ignore_pattern
が含まれているので、あなたドン、私はどのinclude_patterns(「の.dwg」、 『 .DXF』)
コードはすでにそれを行う方法を実証していること。パターンを 'include_patterns'に渡し、戻り値は' copytree'に渡すコールバックです。 'copytree'は、ツリーを横断するときにパスと名前を結果の' _ignore_patterns'関数に渡す作業を行います。 – ShadowRanger
こんにちは@ShadowRanger私は今、以下の仕組みを理解しています。 include_patternsに基づいて一致するものがあれば、ツリーをコピーするためだけに以下を修正して、空のディレクトリにならないように修正する必要があります。 –