file-magic 获取文件的类型

发布时间: 更新时间: 总字数:267 阅读时间:1m 作者:IP:上海 网址

file-magic库是基于 libmagic 的实现 Python ctypes 接口,用来获取文件的类型。

file-magic 介绍

MIME(Multipurpose Internet Mail Extensions, 多用途互联网邮件扩展类型) 是设定某种扩展名的文件用一种应用程序来打开的方式类型

安装

bash
pip install file-magic

使用

python
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

python
import mimetypes

print(mimetypes.guess_type(filename)[0])

filetype

python
import filetype

kind = filetype.guess(file_path)

png 图像文件

python
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 实现

参考

  1. https://pypi.org/project/file-magic/
  2. https://darwinsys.com/file/