使用 Python 将文件夹及其子文件夹中的 .npz 文件全部复制到其他某个文件夹

using Python to copy .npz files from a folder and its subfolders, all to some other single folder

以下代码复制文件夹 C 中的所有 .npz 文件:/Users/toTEST 到文件夹 C :/Users/archive

import glob
import shutil
dest_dir = "C:/Users/archive"
for file in glob.glob(r'C:/Users/toTEST/*.npz'):
    print(file)
    shutil.copy(file, dest_dir)

但是toTEST文件夹下有几个子文件夹,我也想把他们的.npz文件移动到archive 文件夹。如何有效地实现这一目标?

这似乎可以解决问题:

import shutil
import glob

path = 'C:/Users/toTEST/**/'
dest = 'C:/Users/archive/'
pattern = '*.npz'

selectfiles = glob.glob(path + pattern, recursive=True)

for file in selectfiles:
    shutil.copy2(file, dest)