Python mimetypes.guess_type
Get a media-type suggestion for a filename.
A simple example
mimetypes.guess_type
- Start with Filename a.txt
- Do this Ask for a type hint
- Result Often text/plain
Syntax
mimetypes.guess_type(filename)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyChoose a preview for a text attachment
A help desk receives a file called notes.txt and wants a preview hint. Look up a suggested media type for that name while keeping the actual contents separate from the filename-based guess.
from pathlib import Path
from tempfile import TemporaryDirectory
import mimetypes
with TemporaryDirectory() as folder:
base = Path(folder)
media_type, encoding = mimetypes.guess_type("notes.txt")
print(media_type)
text/plain
The known text extension maps to a plain-text preview.
Choose a reader for a text note
A student sends a plain text file to a preview kiosk. The preview desk checks the usual MIME type associated with this extension on its configured system. Which media type is expected in this exercise?
Open a poster proof
The printer receives a PDF proof and needs to select a viewer. The preview desk checks the usual MIME type associated with this extension on its configured system. Which media type is expected in this exercise?
What to watch for
A guess based on the extension does not validate the file contents.