【问题标题】:How to check file format using io module? [duplicate]如何使用 io 模块检查文件格式? [复制]
【发布时间】:2022-01-26 12:22:10
【问题描述】:

我要检查 (image_file) 变量格式 并验证它是“.png”还是“.jpg”。

image_str = urlopen(url).read()
image_file = io.BytesIO(image_str)

url 是来自 reddit 的随机文件。

【问题讨论】:

    标签: python file-io io


    【解决方案1】:

    最好的库可能是imghdr,它检查图像并识别它们的文件类型:

    import imghdr
    
    imghdr.what("/path/to/file")
    # OR...
    imghdr.what("", h=io.BytesIO(imge_str))
    

    该库的文档在这里:https://docs.python.org/3/library/imghdr.html

    【讨论】:

      【解决方案2】:

      您可以使用endswith

      在您的情况下,如果 url 是您文件中的字符串,您可以使用:

      if url.endswith('.png'):
          ...
      elif url.endswith('.jpg'):
          ...
      

      【讨论】:

      • 谢谢我这样做了
      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 2016-12-11
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2019-10-20
      相关资源
      最近更新 更多