前言:接触magic module是由于工作中对的文件类型判断需求,网上查了下,python内置的有mimetypes module,filetype module,与使用mimetypes库相比,更可靠的方法是使用magic软件包。
magic
magic是libmagic文件标识库的封装,libmagic是一个根据文件头识别文件类型的开发库,因此可以实现对文件类型的判断,在Django上,还可以确保MIME类型与UploadedFile.content_type相匹配。
libmagic
module name: magic
install:
python setup.py install # or
easy_install . # or
pip install file-magic
Usage:
import magic
detected = magic.detect_from_filename('magic.py')
print 'Detected MIME type: {}'.format(detected.mime_type)
print 'Detected encoding: {}'.format(detected.encoding)
print 'Detected file type name: {}'.format(detected.name)
确定文件mime-type时,选择的工具简称为其后端称为libmagic。如果您想将任何libmagic绑定与python一起使用,则需要使用此工具,该工具已经附带了自己的python绑定