-5

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/'

1 Answers1

1
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
Vikrant Sharma
  • 419
  • 3
  • 6
  • I tried the code `import os import random for folder in 'owais_images_dataset/donuts': files = os.listdir('owais_images_dataset/donuts') files = random.sample(files, 900) for file in files: f = os.path.join("owais_images_dataset/donuts", "") os.remove(f) ` and got the following error ` os.remove(f) # Remove the file PermissionError: [Errno 1] Operation not permitted: 'owais_images_dataset/donuts/' ` – Owais Qayum Oct 16 '18 at 16:20
  • One: Python is whitespace-indented. The code you added is not properly indented. Two: do you really have the appropriate permissions? Use `sudo` if you know what you are doing. – Vikrant Sharma Oct 16 '18 at 16:34