-5

我有 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/'
4

1 回答 1

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
于 2018-10-16T16:02:36.257 回答