简体   繁体   中英

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 (ie the 7th image in this case) from each sub-folder (windows file arrangement) to a new folder.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM