如何从python中的所有文件中过滤出mimetype JSON

2024-03-28 09:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写python脚本,从dir获取一个接一个的文件,并获取它的mimetype如果它的mimetype不是JSON,那么我想忽略它。请看下面我的部分脚本

for filepath in files:
    filename = os.path.basename(filepath)

    mimetype = mimetypes.guess_type(filepath, strict=False) //here i want to filter out only JSON file and ignore other one

    version = "0"
    checksum = "0"
    fileext = os.path.splitext(filename)[1].lower()     
    # get raw file data
    with open(filepath, "rb") as fr:
        filedata = fr.read()

    oldfilesize = len(filedata)

请参阅我在上述代码中的注释。。有什么解决办法吗???你知道吗


Tags: 文件pathin脚本jsonforosdir
2条回答

你可以这样做:

for filepath in files:
    filename = os.path.basename(filepath)

    mimetype = mimetypes.guess_type(filepath, strict=False)
    if mimetype != ('application/json', None):
    with open(filepath) as f:
        try:
            json.load(f)
        except ValueError:
            # It's not json
            continue
    # do stuff

但如果文件太多和/或太大,这可能会导致效率低下。你知道吗

嗯,mimetypes不会有帮助,因为.json文件的mime类型application/json不是文件元数据固有的。相反,您可以使用它来向处理它的人提供文件类型信息,例如HTTP响应头中的Content-Type: application/json告诉客户机它是JSON。你知道吗

不管怎样,解决方法可能如下:

import json
with open("filename", "rt") as f:
    try:
        d = json.load(f)  # no need to name it if you are just checking
    except JSONDecodeError:
        # handle it or just pass
    else:
        # Got a json file, do whatever

相关问题 更多 >