检查当前目录下损坏的图片文件并删除

# 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

你可能感兴趣的:(python)