Search code examples
globsubdirectoryshutil

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


The following code copies all .npz files in folder C:/Users/toTEST into folder 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)

But the toTEST folder has several subfolders, and I would also like to move their .npz files into the archive folder as well. How can this be efficiently achieved?


Solution

  • This seems to do the trick:

    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)