How do I delete all png format pics in a folder using Python 3?
Python 3 How to delete images in a folder
Asked Answered
Did any of these answers resolve your question? –
Noelianoell
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')
+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 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
there's a space between
removing
and files
. this answer is doomed to fail. –
Unemployed 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
'
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
If the file is in the same path as the program then,
import os
os.remove('file.png')
no path required.
© 2022 - 2025 — McMap. All rights reserved.