最近需要根据txt中的文件名,找到对应的图片,并放到对应文件夹。(和划分数据集有关)写了下面这段代码实现。
import os
import shutil
list_path='/home/zhouyf/insky_work/pythonProject/ImageSets/Main'
src_img_path='/home/zhouyf/insky_work/pythonProject/images'
to_img_path='/home/zhouyf/insky_work/pythonProject/ImageSets/image'
for type in os.listdir(list_path):
names = []
print(type)
with open(list_path+'/'+type, 'r') as file_to_read:
while True:
name = file_to_read.readline()
if not name:
break
name = name.strip('\n')
names.append(name)
#print(names)
for name in names:
for file in os.listdir(src_img_path):
if os.path.isfile(src_img_path+'/'+file):
if name in file:
if not os.path.exists(to_img_path + '/' + type[0:-4]):
os.mkdir(to_img_path + '/' + type[0:-4])
shutil.copy(src_img_path + '/' + file, to_img_path + '/' + type[0:-4]+ '/'+file)
print(name+'.jpg')