[Python] filetype infers the file type according to the content

Micro cold 2022-05-14 14:13:29 阅读数:552

pythonfiletypeinfersfiletype

filetype The function of is based on the content of the file , Guess the file type .

This module does not belong to the standard library , But because of the imghdr and sndhdr stay 3.13 Will be removed from the version , and filetype Then be PEP594 Indicate that it is a substitute for these two modules .

But this succedaneum The function of is quite powerful , And the call method is very simple

Install first

pip install filetype

And then call

import filetype
kind = filetype.guess('test.jpg')
if kind is None:
print("guess error")
else:
print(f"File extension is {
kind.extension}")
print(f"File MIME type is {
kind.mime}")

The output is

File extension is jpg
File MIME type is image/jpeg

filetype Module support 60 More than file types , The following table lists the extensions for different file types

ImageVideoAudioArchiveArchiveFont
dwgmp4aacbreotwoff
xcfm4vmid7zdcmwoff2
jpgmkvmp3xzsqlitettf
jpxwebmm4aarnesotf
pngmovoggzipcrx
apngaviflactarcab
gifwmvwavrardeb
webpmpgamrgzrpm
cr2flvaiffbz2exe
tifZswf
bmplzops
jxrlzrtf
psdlz4epub
icopdf
heic

Besides, there are wasm.

版权声明:本文为[Micro cold]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141409332372.html