Vannaro
Vannaro

Reputation: 83

Remove images in multiple folders (Python)

I want to write a python script to randomly keep only some images in multiple folders.

I am new to python, and I am trying to find the solution. However, I could not find a good one to start with yet. I would appreciate it if anyone could help me. Thank you.

Upvotes: 0

Views: 289

Answers (1)

Arhiliuc Cristina
Arhiliuc Cristina

Reputation: 323

This might help you. It firstly retrieves the list of all directories, and afterwards removing random files to get only n files. Note: path_to_all_images_folder has to be declared

import os
import random
def keep_n_dir(directory, n):
    files = os.listdir(directory) #You retrieve the list of names of files
    if len(files) > n: #If you already have less than n files, you do nothing
        diff = len(files) - n
        files_to_delete = random.sample(files, k=diff) #Random sample files to delete
        for file in files_to_delete: 
            os.remove(os.path.join(directory, file)) #Delete additional files

directories = os.listdir(path_to_all_images_folder)
directories = [os.path.join(path_to_all_images_folder, folder) for folder in directories]
for directory in directories:
    if os.path.isdir(directory):
        keep_n_dir(directory, n)

ATTENTION! This code removes from the directory the other files. It only keeps n.

Upvotes: 2

Related Questions