file-magic库是基于 libmagic 的实现 Python ctypes 接口,用来获取文件的类型。
file-magic 介绍
MIME(Multipurpose Internet Mail Extensions, 多用途互联网邮件扩展类型) 是设定某种扩展名的文件用一种应用程序来打开的方式类型
安装
pip install file-magic使用
import magic
# file-magic 库核心 API 为 detect_from_filename、detect_from_content 与 detect_from_fobj
detected = magic.detect_from_filename('magic.py')
print(f'Detected MIME type: {detected.mime_type}')
print(f'Detected encoding: {detected.encoding}')
print(f'Detected file type name: {detected.name}')
with open("magic.py", "rb") as f:
content_info = magic.detect_from_content(f.read(1024))
print(f'Detected from content: {content_info.name}')
# 注:若使用的是 python-magic 库(pip install python-magic),则 API 为:
# type_info = magic.from_file("magic.py")
# type_info = magic.from_buffer(open("magic.py", 'rb').read(1024))扩展
mimetypes
import mimetypes
print(mimetypes.guess_type(filename)[0])filetype
import filetype
kind = filetype.guess(file_path)png 图像文件
with open('1.png','rb') as f:
x = f.read(24)
width = x[16:20]
print(int.from_bytes(width, 'big'))
height = x[20:24]
print(int.from_bytes(height, 'big'))
struct.unpack('i', height)Golang 实现
- gabriel-vasile/mimetype
- h2non/filetype 通过文件 magic code 判断文件类型,参考
参考
最近更新
最新评论