如何使用 python 从多个文件夹中删除多个图像

How can i delete multiple images from multiple folders using python

我有 100 个文件夹,每个文件夹有 1000 张图片。我需要从每个文件夹中删除 900 张图像。

图片可以随机删除,我需要在每个文件夹中保留100张图片。

是否有任何 python 脚本可以提供帮助。

我试过下面的代码

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

遇到这个错误

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