pip install python-magic
pip install python-magic-bin
代码
# encoding=utf-8
import magic #pip install python-magic python-magic-bin
type_info = magic.from_file("./data/123.pdf")
print('file_type: %s' % type_info)#file_type: PDF document, version 1.6
type_info = magic.from_buffer(open("./data/123.pdf",'rb').read(1024))
print('file_type: %s' % type_info)#file_type: PDF document, version 1.6
type_info = magic.from_file("./data/123.pdf", mime=True)
print('file_type: %s' % type_info)#file_type: application/pdf
需要注意的是,这种方法路径中不能出现中文,否则会报错
def distinguish_MIME_type(file_path): #查看文件的MIME格式类型(支持中文)
import magic # pip install python-magic python-magic-bin
mime_type = magic.from_buffer(open(file_path, 'rb').read(1024), mime=True)
return mime_type
file_path = 'E:/Documents/Desktop/中国.jpg' #获得选择好的文件
file_type = distinguish_MIME_type(file_path)
print("file_type:", file_type)
magic不支持中文路径的文件名
那就不要单纯使用文件名来判断了,而是使用打开文件的方式来判断
import magic #pip install python-magic python-magic-bin
file_path = 'E:/Documents/Desktop/中国.jpg' #获得选择好的文件
type_info = magic.from_buffer(open(file_path,'rb').read(1024), mime=True)