如何使用 Python 递归复制目录中具有特定扩展名的所有文件?

How to recursively copy all files with a certain extension in a directory using Python?

我正在尝试编写一个 Python 函数,将目录及其子目录中的所有 .bmp 文件复制到指定的目标目录中。

我试过使用 os.walk 但它只到达第一个子目录然后停止。这是我目前所拥有的:

def copy(src, dest):

    for root, dirs, files in os.walk(src):
        for file in files:
            if file[-4:].lower() == '.bmp':
                shutil.copy(os.path.join(root, file), os.path.join(dest, file))

我需要更改什么才能从每个子目录复制每个 .bmp 文件?

编辑:这段代码确实有效,源目录中的位图文件比预期的要少。但是,对于我正在编写的程序,我更喜欢下面显示的使用 glob 的方法。

如果我没理解错的话,你想要 globrecursive=True,它与 ** 说明符一起,将递归遍历目录并找到所有满足格式说明符的文件:

import glob
import os
import shutil

def copy(src, dest):
    for file_path in glob.glob(os.path.join(src, '**', '*.bmp'), recursive=True):
        new_path = os.path.join(dest, os.path.basename(file_path))
        shutil.copy(file_path, new_path)