Library contents

Python mimetypes.guess_type

Get a media-type suggestion for a filename.

A simple example

mimetypes.guess_type

  1. Start with Filename a.txt
  2. Do this Ask for a type hint
  3. Result Often text/plain
The extension suggests plain text. Detection depends on the platform and its type database.

Syntax

Python 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.py

Choose 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.

Resulttext/plain
lesson.py
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)
Output
text/plain

The known text extension maps to a plain-text preview.

Advertisements

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?

Givencrib.txt · standard MIME mapping
Worked resulttext/plain

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?

Givenposter.pdf · standard MIME mapping
Worked resultapplication/pdf

What to watch for

A guess based on the extension does not validate the file contents.

Documentation for mimetypes.guess_type