Search code examples
pythondatasetclassificationdirectory-structure

How to copy specific files from the sub-folders to a new folder in python?


I have a folder with several sub-folders, each containing the same number of files (here it is 7). The code that I use at the present copies all the files from the different sub-folders within a main folder, to another new folder.

import os
import shutil

src = r'C:\Users\datasets\test\0'
dest = r'C:\Users\datasets\data_new\test\0'

for path, subdirs, files in os.walk(src):
    for name in files:
        filename = os.path.join(path, name)
        shutil.copy2(filename, dest)

I need to modify the code in a way to copy only the last image (i.e. the 7th image in this case) from each sub-folder (windows file arrangement) to a new folder.


Solution

  • This should do it for you.

    import os
    import shutil
    from glob import glob
    
    src = r'C:\temp\datasets\test\0'
    dest = r'C:\temp\datasets\data_new\test\0'
    
    for base, dirs, _ in os.walk(src):
        for path in dirs:
            files = sorted(glob(os.path.join(base, path, '*')))
            if len(files) == 0:
                continue
            file = files[-1]
            filename = os.path.join(path, file)
            shutil.copyfile(filename, dest)