ah bon
ah bon

Reputation: 10011

How to randomly select images and put them to multiple folders in Python

I have a directory with following images, and I want to randomly select 3 images and put them in multiple folders say: folder 1, 2, and 3 etc. How can i do it in Python? Thanks.

enter image description here

I have tried so far:

import os, random
import shutil 
import glob


folder = "C:/Users/User/Desktop/Image"
a=random.choice(os.listdir(folder))
print(a)

src_dir = "C:/Users/User/Desktop/Image"
dst_dir = "C:/Users/User/Desktop/Image/1"
for jpgfile in glob.iglob(os.path.join(src_dir, "*.jpg")):
    shutil.copy(jpgfile, dst_dir)

Upvotes: 2

Views: 10536

Answers (2)

ah bon
ah bon

Reputation: 10011

Problem solved.

import os, random
import shutil

m = 3
n = 3

src_dir = "C:/Users/User/Desktop/test/source/"
dst_dir = "C:/Users/User/Desktop/test/destination/"

file_list = os.listdir(src_dir)

for i in range(m):
    for j in range(n):
        a = random.choice(file_list)
        #file_list.remove(a)
        shutil.copy(src_dir + a, dst_dir + str(i+1) + "/" + a)

Upvotes: 0

iz_
iz_

Reputation: 16593

Try this:

import os
import shutil
import glob
import random

to_be_moved = random.sample(glob.glob("C:/Users/User/Desktop/Image/*.jpg"), 3):

for f in enumerate(to_be_moved, 1):
    dest = os.path.join("C:/Users/User/Desktop", str(f[0]))
    if not os.path.exists(dest):
        os.makedirs(dest)
    shutil.copy(f[1], dest)

Upvotes: 4

Related Questions