Python实现遍历文件夹下是否包含中文字符及图片格式是否正确

# -*- coding: UTF-8 -*-
import os
import sys
import imghdr
#检查是否包含中文字符
def is_contain_chinese(check_str):
    try:
        for ch in check_str:
            if u'\u4e00' <= ch <= u'\u9fff' or ch == " ":
                raise Exception("error path")
    except Exception as err:
        print("error path = ", check_str)
#检查图片后缀名与实际格式是否一致
def is_format_correct(filepath):
    suffix = filepath.split(".")[1]
    imgType = imghdr.what(filepath)
    if (imgType == 'png' or imgType == 'jpg') and imgType != suffix:
        print("filepath = ", filepath)
        raise Exception("format error")

def walkFile(path):
    filelist = os.listdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            walkFile(filepath)
        else:
            is_contain_chinese(filepath)
            is_format_correct(filepath)
                



def main():
    dirct = os.getcwd() # 获取当前工作目录路径
    files = os.listdir(dirct)  # 文件夹下所有目录的列表
    lang = ""
    source = ""
    for f in files:
        if "res" in f :
            source = f

    sourceDir = os.path.join(dirct, source)
    print("sourceDir = ", sourceDir)
    walkFile(sourceDir)


if __name__ == '__main__':
    main()

在该py脚本同级目录下创建res文件夹,运行脚本会检查res下的所有文件。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容