pythonimagedirectorypicturegallery

How can i delete multiple images from multiple folders using python


I am having 100 folders and each folder is having 1000 images. i need to delete 900 images from each folder.

The images deleting can be random and i need 100 images to be left in each folder.

Is there any python script that can help.

i tried the following code

import os
import random

for folder in 'owais_images_dataset/donuts':  # Go over each folder path
files = os.listdir('owais_images_dataset/donuts')  # Get filenames in current folder
files = random.sample(files, 900)  # Pick 900 random files
for file in files:  # Go over each file name to be deleted
    f = os.path.join("owais_images_dataset/donuts", "")  # Create valid path to file
    os.remove(f)  # Remove the file

and got this error

PermissionError                           Traceback (most recent call last)
<ipython-input-26-b1f2c957d985> in <module>()
  7     for file in files:  
  8         f = os.path.join("owais_images_dataset/donuts", "") 
  9         os.remove(f)  
  PermissionError: [Errno 1] Operation not permitted: 
  'owais_images_dataset/donuts/'

Solution

  • import os
    import random
    
    for folder in folder_paths:  # Go over each folder path
        files = os.listdir(folder)  # Get filenames in current folder
        files = random.sample(files, 900)  # Pick 900 random files
        for file in files:  # Go over each file name to be deleted
            f = os.path.join(folder, file)  # Create valid path to file
            os.remove(f)  # Remove the file