python同步实现图片文件夹和标签文件夹的随机乱序(虽然乱序 但是图片和标签对应名相同)
import os
import random
import re
import shutil
image_dir = r'C:\Users\xjj\Desktop\fsdownload\bulid\test\images\\'
img_name_list = os.listdir(image_dir)
label_dir = r'C:\Users\xjj\Desktop\fsdownload\bulid\test\labels\\'
label_name_list = os.listdir(label_dir)
result_dir = r'C:\Users\xjj\Desktop\fsdownload\bulid\images\\'
result_label = r'C:\Users\xjj\Desktop\fsdownload\bulid\labels\\'
if not os.path.exists(result_dir):
os.makedirs(result_dir)
print(f'创建文件夹{result_dir}成功!')
random_len = len(img_name_list)
img_index = [i for i in range(random_len)]
random.shuffle(img_index)
img_list = []
for i, img in enumerate(img_name_list):
dot_index = img.find('.')
front = img.split('.')[0]
if dot_index > 0:
img_name = str(img_index[i]) +'_'+str(front)+ img[dot_index:]
img_list.append(img_name)
shutil.copyfile(image_dir + img, result_dir + img_name)
for i,value in enumerate(label_name_list):
if(img_list[i].split('_')[1] in label_name_list):
shutil.copyfile(label_dir + value, result_label + img_list[i])
|