[英]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).我有一个包含多个子文件夹的文件夹,每个子文件夹包含相同数量的文件(这里是 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.我需要以某种方式修改代码,以便仅将每个子文件夹(Windows 文件排列)中的最后一个图像(即本例中的第 7 个图像)复制到新文件夹中。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.