Python 将一个文件夹下图片分到多个文件夹下

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# 将一个文件夹下图片按比例分在两个文件夹下,比例改0.7这个值即可
import os
import random
import shutil
from shutil import copy2
trainfiles = os.listdir('D:/ceshi/data') #(图片文件夹)
#print(trainfiles)
trainfiles.sort()
# print(trainfiles)
# print(trainfiles[0])
num_train = len(trainfiles)
print( "num_train: " + str(num_train) )
index_list = list(range(num_train))
#print(index_list) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
# random.shuffle(index_list)
num = 0
lj1 = 'D:/ceshi/1' #(将图片文件夹中的7份放在这个文件夹下)
lj2 = 'D:/ceshi/2' #(将图片文件夹中的3份放在这个文件夹下)
lj3 = 'D:/ceshi/3' #(将图片文件夹中的7份放在这个文件夹下)
lj4 = 'D:/ceshi/4' #(将图片文件夹中的3份放在这个文件夹下)
lj5 = 'D:/ceshi/5' #(将图片文件夹中的7份放在这个文件夹下)


for i in index_list:
    fileName = os.path.join('D:/ceshi/data', trainfiles[i])
    #print(trainfiles[i])
    if num < num_train*0.2:
        #print(str(fileName))
        copy2(fileName, lj1)
    elif num_train*0.2 <= num < num_train*0.4:
        copy2(fileName, lj2)
    elif num_train*0.4 <= num < num_train*0.6:
        copy2(fileName, lj3)
    elif num_train*0.6 <= num < num_train*0.8:
        copy2(fileName, lj4)
    else:
        copy2(fileName, lj5)
    num += 1

你可能感兴趣的:(Python 将一个文件夹下图片分到多个文件夹下)