1. 程式人生 > >檢查當前目錄下損壞的圖片檔案並刪除

檢查當前目錄下損壞的圖片檔案並刪除

# encoding: UTF-8
#
# Project: CheckImages
# Author: borlittle
# CreateDate: 2018/6/9
"""
  BriefIntroduction:
  Update:
  Reference:
  RunningEnvironment: python 3.5 and above  
"""
# import packages
from PIL import Image
import os

# just for unit test
if __name__ == '__main__':

    badFilesList = []
    curDir = '.'
for root, dirs, files in os.walk(curDir): # print(files) # 檢查當前目錄中的損壞的圖片檔案 for each in files: # for each in os.listdir('./'): if each.endswith('.png') or each.endswith('.jpg') or each.endswith('.gif') or each.endswith( '.JPG') or each.endswith('.PNG') or
each.endswith('.GIF') or each.endswith( '.jpeg') or each.endswith( '.JPEG'): # print(each) try: im = Image.open(os.path.join(root, each)) # im.show() except Exception as e: print('Bad file:', os.path.join(root, each)) badFilesList.append(os.path.join(root, each)) #
刪除損壞的檔案 if len(badFilesList) != 0: for each in badFilesList: try: os.remove(each) except Exception as e: print('Del file: %s failed, %s' % (each, e)) pass