【Python】图片有效性管理

# -*- coding: UTF-8 -*-

import os
import imghdr

def get_filelist(dir):
    for home, dirs, files in os.walk(dir):
        for filename in files:
            try:
                fullname = os.path.join(home, filename)
                filesize = os.path.getsize(fullname) 
                # print(fullname + ",文件大小为 "+  str(filesize))
                if filesize < 1 :
                    print(fullname + ",错误文件大小为 "+  str(filesize))
                    try:
                        os.remove(fullname)
                        print("删除成功" + fullname)
                    except:
                        print("删除失败" + fullname)
                elif filesize < 1024 :
                    if imghdr.what(fullname):
                        # good image
                        print(fullname + " is OK")
                    else:
                        # bad image
                        print(fullname + ",无效文件大小为 "+  str(filesize))
                        try:
                            os.remove(fullname)
                            print("删除成功" + fullname)
                        except:
                            print("删除失败" + fullname)
            except:
                print("属性获取失败," + fullname)                            


if __name__ == "__main__":
    get_filelist("E:\\15")

 

posted @ 2021-02-26 11:29  咸鱼翻身  阅读(168)  评论(0编辑  收藏  举报