Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีหา MIME Type ของไฟล์ใน Python

Python มีโมดูลชื่อ mimetypes ที่คุณสามารถใช้ Guess MIME Type ของไฟล์ใน Python ได้ อย่างไรก็ตาม มันไม่ใช่วิธีที่น่าเชื่อถือในการรู้ MIME Type ของไฟล์

ตัวอย่าง

>>> import mimetypes
>>> print(mimetypes.MimeTypes().guess_type('my_file.txt')[0])
text/plain

คุณยังสามารถใช้ Non-standard Module ชื่อ python-magic เพื่อ Deduced MIME Type ของไฟล์

ตัวอย่าง

>>> import magic
>>> mime = magic.Magic(mime=True)
>>> mime.from_file("my_file.txt")
text/plain