mimetypes 是 [[Python]] 标准库的实现,用于获取文件的 MIME 类型。
对象
guess_type
语法: `mimetypes.guess_type(url, strict=True)
- url: 可以是 URL 或文件路径
- strict: 是否严格检查 URL 是否为有效 URL
返回值:
- 元组 (type, encoding)
- type: 文件的 MIME 类型
- encoding: 文件的编码
使用
检测文件是否为图片
使用 mimetypes 判断比列举所有图片类型更简单。
import mimetypes
mime_type, _ = mimetypes.guess_type("test.png")
if mime_type.startswith("image/"): print("文件是图片")else: print("文件不是图片")