shutil.copytree without files

前端 未结 5 2105
刺人心
刺人心 2021-02-13 19:39

I\'m trying use shutil.copytree:

shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=None)

This copy also files in folder. I need copy only folders

5条回答
  •  一生所求
    2021-02-13 20:19

    If you want ignore pattern functionality with os.walk(), then:

    ignorePatterns=[".git"]
    def create_empty_dirtree(src, dest, onerror=None):
        src = os.path.abspath(src)
        src_prefix = len(src) + len(os.path.sep)
        for root, dirs, files in os.walk(src, onerror=onerror):
            for pattern in ignorePatterns:
                if pattern in root:
                    break
            else:
                #If the above break didn't work, this part will be executed
                for dirname in dirs:
                    for pattern in ignorePatterns:
                        if pattern in dirname:
                            break
                    else:
                        #If the above break didn't work, this part will be executed
                        dirpath = os.path.join(dest, root[src_prefix:], dirname)
                        try:
                            os.makedirs(dirpath,exist_ok=True)
                        except OSError as e:
                            if onerror is not None:
                                onerror(e)
                    continue #If the above else didn't executed, this will be reached
    
            continue #If the above else didn't executed, this will be reached
    

    This will ignore .git directory.

    Note: This requires Python >=3.2 as I used the exist_ok option with makedirs which isn't available on older versions.

提交回复
热议问题