# iterate files over subdirectories in `00_store`, store image files in hash table, delete files with same hash import os import hashlib import imghdr deleted = 0 def is_image(filename, verbose=False): data = open(filename, "rb").read(10) # check if file is JPG or JPEG if data[:3] == b"\xff\xd8\xff": if verbose == True: print(filename + " is: JPG/JPEG.") return True # check if file is PNG if data[:8] == b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a": if verbose == True: print(filename + " is: PNG.") return True # check if file is GIF if data[:6] in [b"\x47\x49\x46\x38\x37\x61", b"\x47\x49\x46\x38\x39\x61"]: if verbose == True: print(filename + " is: GIF.") return True return False def action(in_path): for root, _, files in os.walk(in_path): for file in files: file_path = os.path.join(root, file) print(file_path) with open(file_path, "rb") as f: if is_image(file_path): # it's a jpeg pass else: # print(file_path, "is not valid jpeg") os.remove(file_path) CURR_DIR = os.path.dirname(os.path.abspath(__file__)) action(CURR_DIR + "/data/train") action(CURR_DIR + "/data/validate")