0

How to delete image/video files in python 3? I know how to delete them when we know the name of image/video, however when I don't know the name of image in some file/folder how can I delete it with the help of their formats like .jpg/.mp4.

I tried to follow the steps suggested in other question wit no luck,

>>> os.remove("C:\Program Files\Python36\*.png")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 123] The filename, directory name, or volume label syntax 
is incorrect: 'C:\\Program Files\\Python36\\*.png'

os.remove("C:\Program Files\Python36\INC0077896.png") #here I am able to delete image

Abhijit
  • 53
  • 1
  • 7

1 Answers1

3

No, os.system returns the command return code. Since rm wasn't found, (you're probably using windows), it returns 1

no need for system commands for that (not portable, among other inconvenients) . Use glob:

import glob
for i in glob.glob("*.png"):
    os.remove(i)

for a different directory & unprotect file before removing (useful on windows) and exception handling (in case there's a directory called xxx.jpg):

import glob,os
for i in glob.glob(os.path.join(directory,"*.png")):
    try:
       os.chmod(i,0o777)
       os.remove(i)
    except OSError:
       pass
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219