Skip to content

Instantly share code, notes, and snippets.

@3lbios
Created March 29, 2020 23:30
Show Gist options
  • Save 3lbios/74533e21109820bfa171038c3942d8c1 to your computer and use it in GitHub Desktop.
Save 3lbios/74533e21109820bfa171038c3942d8c1 to your computer and use it in GitHub Desktop.
Script to remove corrupted image files
import PIL
from PIL import Image as ImageP
import glob
import os
dir_to_scan = "DIR_WITH_TRAILING_SLASH"
allpics = 0
goodpics = 0
good_filenames = []
bad_filenames = []
for filename in glob.iglob(dir_to_scan + "**/*.jpg", recursive=True):
allpics += 1
good = True
img = None
try:
img = ImageP.open(filename)
except:
good = False
if good:
try:
img.verify()
except:
good = False
if good:
goodpics += 1
good_filenames.append(filename)
else:
bad_filenames.append(filename)
if img:
img.close()
print(str(allpics))
print(str(goodpics))
print(str(allpics-goodpics))
for b in bad_filenames:
try:
os.remove(b)
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment