Python 3 How to delete images in a folder
Asked Answered
C

4

12

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

Confiding answered 28/6, 2013 at 6:41 Comment(1)
Did any of these answers resolve your question?Noelianoell
N
20

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')
Noelianoell answered 28/6, 2013 at 6:46 Comment(5)
+1 for os.remove(), but I suggest not to use the file identifier for the purpose. It actually is a filename or fname. Moreover, even though the file lost the meaning it had in Python 2, it may be still confusing to use the identifier for another purpose.Swanherd
I could not get os.remove() to work as described: >>> os.remove(kml_fn) for kml_fn in os.listdir(kml_owner_directory) if kml_fn.endswith('.kml') File "<stdin>", line 1 os.remove(kml_fn) for kml_fn in os.listdir(kml_owner_directory) if kml_fn.endswith('.kml')Ablation
Hi, I am using python 3.8. Got error: statements must be separated by newlines or semicolons.Unsettle
Thanks a lot! But in my case, I need to wrap this code into the generator like [...]Revkah
You also need to provide the full path: os.remove(os.path.join('path/to/directory', file))Unemployed
A
4
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

Athene answered 3/1, 2022 at 15:8 Comment(1)
there's a space between removing and files. this answer is doomed to fail.Unemployed
P
2

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

'

Physicality answered 15/2, 2018 at 11:54 Comment(1)
Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.Emmeram
J
-2

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

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

no path required.

Jade answered 12/4, 2024 at 12:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.