使用Python基于通配符以递归方式将文件从源复制到目标

时间:2018-02-22 04:37:22

标签: python

我有一个源目录,在嵌套位置有几个xml文件。我正在尝试编写一个python脚本,以基于模式(例如* 1.2.3.xml)递归复制文件到目标位置。

source
├── master.1.2.3.xml
    └── directory
           └── fileA.1.2.3.xml
           ├── fileA.1.2.5.xml
           ├── fileB.1.2.3.xml

预期结果:

target
├── master.1.2.3.xml
    └── directory
           └── fileA.1.2.3.xml
           ├── fileB.1.2.3.xml

以下脚本不进行过滤。

from shutil import copytree
def ignored_files(adir,filenames):
    return [filename for filename in filenames if not filename.endswith('1.2.3.xml')]
copytree(source, target, ignore=ignored_files)

我在这里缺少什么?

3 个答案:

答案 0 :(得分:3)

这里发生的事情是copytree函数将递归工作。首先,它将下载到源代码并为文件名arg提供ignored_files()两个项目 - [master.1.2.3.xml, directory]

ignored_files将返回[directory],因为它与模式不匹配,因此copytree将忽略整个目录本身。

您必须在ignored_files() os.path.isdir()之类的内容中为您的条件添加额外的检查。

答案 1 :(得分:1)

你能试试吗?

import glob
import shutil
dest_dir = "path/to/dir"
for file in glob.glob(r'/path/to/dir/*1.2.3.xml'):
    print(file)
    shutil.copy(file, dest_dir)

答案 2 :(得分:0)

尝试以下方法:

def copy_tree_with_wildcards(src: str, dest: str, pattern: str):
src = os.path.abspath(src)
for filename in glob.iglob(src + '/**/' + pattern, recursive=True):
    src_file = os.path.join(src, filename)
    dest_file = dest + filename[len(src):]
    dest_dir = os.path.dirname(dest_file)
    os.makedirs(dest_dir, exist_ok=True)
    if os.path.isfile(src_file):
        shutil.copy(src_file, dest_file)