【问题标题】:How can i filter out mimetype JSON only from no of files in python如何仅从 python 中的文件中过滤出 mimetype JSON
【发布时间】:2016-04-16 12:57:19
【问题描述】:

我正在编写 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)

在上面的代码中查看我的评论..任何解决方案???

【问题讨论】:

  • 您无法真正“获取文件的 mimetype”,因为这不是系统维护的元数据。您可以尝试通过文件扩展名来识别 JSON 文档(查找 .json),但是通过检查很难识别 JSON 文件。

标签: python json mime-types


【解决方案1】:

你可以试试这样的:

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

但是如果有很多文件和/或它们很大,这可能会效率低下。

【讨论】:

    【解决方案2】:

    好吧,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 2020-10-26
      • 2021-09-30
      相关资源
      最近更新 更多