all Python 3mimetypesfunction
mimetypes.guess_extension()
extensions
Picks one extension for a MIME type — for example, to name a downloaded file from its Content-Type header.
Syntax
ext = mimetypes.guess_extension(type, strict=True)
It returns the extension with the dot ('.json', not 'json'), and None for an unknown type, so building a name without a check fails with TypeError. Header parameters get in the way: cut 'text/html; charset=utf-8' down to 'text/html' first. For types with several extensions the pick depends on the version and on system files.
Examples
import mimetypes
db = mimetypes.MimeTypes()
print(db.guess_extension('application/json')) # → .json
print(db.guess_extension('text/html; charset=utf-8')) # → None
print(db.guess_extension('text/html; charset=utf-8'.split(';')[0])) # → .html
See also
Open in the full glossarydocs.python.orgReport an inaccuracy