python拷贝文件夹保持目录格式_将特定文件复制到新文件夹,同时保留原始子目录...

您可以使用(ususing?)对内置的^{}函数执行您想要的操作其可选的ignore关键字参数。棘手的部分是,如果给定,它必须是一个可调用的函数,它返回每个目录中应该而不是应该复制的内容,而不是应该复制的内容。在

但是,可以编写一个类似于^{}的工厂函数来创建一个完成所需操作的函数,并将其用作ignore关键字参数的值。在

返回的函数首先通过^{}函数确定要保存的文件,然后将它们从给定目录中的所有文件的列表中删除,除非它们是子目录名,在这种情况下,它们会留在后面的[递归]处理中。(这就是它复制整个树的原因,以及您试图编写自己的copytree()函数时可能出现的错误)。在#!/usr/bin/env python

# -*- coding: utf-8 -*-

# Works in Python 2.7 & 3.x

import fnmatch

from os.path import isdir, join

def include_patterns(*patterns):

""" Function that can be used as shutil.copytree() ignore parameter that

determines which files *not* to ignore, the inverse of "normal" usage.

This is a factory function that creates a function which can be used as a

callable for copytree()'s ignore argument, *not* ignoring files that match

any of the glob-style patterns provided.

‛patterns’ are a sequence of pattern strings used to identify the files to

include when copying the directory tree.

Example usage:

copytree(src_directory, dst_directory,

ignore=include_patterns('*.sldasm', '*.sldprt'))

"""

def _ignore_patterns(path, all_names):

# Determine names which match one or more patterns (that shouldn't be

# ignored).

keep = (name for pattern in patterns

for name in fnmatch.filter(all_names, pattern))

# Ignore file names which *didn't* match any of the patterns given that

# aren't directory names.

dir_names = (name for name in all_names if isdir(join(path, name)))

return set(all_names) - set(keep) - set(dir_names)

return _ignore_patterns

if __name__ == '__main__':

from shutil import copytree, rmtree

import os

src = r'C:\vols\Files\PythonLib\Stack Overflow'

dst = r'C:\vols\Temp\temp\test'

# Make sure the destination folder does not exist.

if os.path.exists(dst) and os.path.isdir(dst):

print('removing existing directory "{}"'.format(dst))

rmtree(dst, ignore_errors=False)

copytree(src, dst, ignore=include_patterns('*.png', '*.gif'))

print('done')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值