其中用到了libmagic库里的magic,libmagic是一个根据文件头识别文件类型的开发库,python可以利用该库很方便地实现对文件格式的判断。
安装过程:
Python-magic * For Linux: * pip install python-magic * For Mac: * brew install libmagic * pip install python-magic
def _get_filetype(self, data):
"""Gets filetype, uses libmagic if available.
@param data: data to be analyzed.
@return: file type or None.
"""
if not HAVE_MAGIC:
return None
try:
ms = magic.open(magic.MAGIC_NONE)
ms.load()
file_type = ms.buffer(data)
except:
try:
file_type = magic.from_buffer(data)
except Exception:
return None
finally:
try:
ms.close()
except:
pass
return file_type