user2471181
user2471181

Reputation: 163

Python 3 How to delete images in a folder

How do I delete all png format pics in a folder using Python 3?

Upvotes: 12

Views: 69339

Answers (4)

Anagha V Raj
Anagha V Raj

Reputation: 17

If the file is in the same path as the program then,

import os 
os.remove('file.png')

no path required.

Upvotes: -2

Sindeesh Dinesh
Sindeesh Dinesh

Reputation: 71

import glob
removing_files = glob.glob('file path/*.jpg')
for i in removing_files:
    os.remove(i)

replace file path with the directory to the image folder

Upvotes: 4

Smit Mehta
Smit Mehta

Reputation: 101

this function will help you to delete a single image file all you need to do is put it in for loop to delete the multiple images or file..just double check that you are providing valid path to your file. '

def remove_img(self, path, img_name):
    os.remove(path + '/' + img_name)
# check if file exists or not
    if os.path.exists(path + '/' + img_name) is false:
        # file did not exists
        return True

'

Upvotes: 2

zeantsoi
zeantsoi

Reputation: 26203

This single line statement will take each file in a specified path and remove it if the filename ends in .png:

import os
os.remove(file) for file in os.listdir('path/to/directory') if file.endswith('.png')

Upvotes: 20

Related Questions