python 检测判断文件类型 python-magic imghdr filetype

创建日期: 2022-07-26 20:14 | 作者: 风波 | 浏览次数: 21 | 分类: Python

参考:https://www.geeksforgeeks.org/determining-file-format-using-python/

安装

pip install python-magic -i https://mirrors.aliyun.com/pypi/simple/  --trusted-host mirrors.aliyun.com
pip install filetype -i https://mirrors.aliyun.com/pypi/simple/  --trusted-host mirrors.aliyun.com

Debian12

apt install libmagic-dev

macOS 来源:https://github.com/Yelp/elastalert/issues/1927

pip install python-magic-bin -i https://mirrors.aliyun.com/pypi/simple/  --trusted-host mirrors.aliyun.com

python-magic 使用方式

import magic

# printing the human readable type of the file
print(magic.from_file('apple.jpg'))

或者

guess = magic.from_buffer(bdata, mime=True)  # guess="video/mp4"

执行结果

HTML document, ASCII text, with CRLF line terminators

输出 mime

# printing the mime type of the file
print(magic.from_file('apple.jpg', mime = True))

执行结果:

text/html

imghdr 使用方式

来源:https://stackoverflow.com/questions/22493063/python-how-to-use-stringio-with-imghdr-to-determine-if-valid-image

with open(filepath, 'rb') as fd:
    guess = imghdr.what(fd)

文件的二进制数据

guess = imghdr.what(None, bdata)

filetype 使用方式

来源:https://pypi.org/project/filetype/

安装

pip install filetype  -i https://mirrors.aliyun.com/pypi/simple/  --trusted-host mirrors.aliyun.com

使用

import filetype

def main():
    kind = filetype.guess('tests/fixtures/sample.jpg') # 文件 path,或文件二进制数据
    if kind is None:
        print('Cannot guess file type!')
        return

    print('File extension: %s' % kind.extension)
    print('File MIME type: %s' % kind.mime)

if __name__ == '__main__':
    main()

支持的类型

Image

Video

Audio

Archive

Document

Font

Application

21 浏览
8 爬虫
0 评论