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

时间:2018-10-16 15:48:16

标签: python image directory picturegallery

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

1 个答案:

答案 0 :(得分:0)

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