Python Glossary Русский

all Python 3mimetypesfunction

mimetypes.guess_type()

guessing the type

Guesses the MIME type and compression encoding from a file name or URL. Returns a (type, encoding) pair and never reads the file contents.

Syntax

mimetype, encoding = mimetypes.guess_type(url, strict=True)

The result is always a two-item tuple, not a string: for 'a.tar.gz' it is ('application/x-tar', 'gzip') — the second part is about compression, not text encoding. The type comes from the extension alone: a renamed file fools it, and a name without an extension gives (None, None). Extension case does not matter. Since 3.13, guess_file_type() is preferred for paths on disk.

Examples

import mimetypes
print(mimetypes.guess_type('page.html'))  # → ('text/html', None)
print(mimetypes.guess_type('backup.tar.gz'))  # → ('application/x-tar', 'gzip')
print(mimetypes.guess_type('IMAGE.PNG'))  # → ('image/png', None)
print(mimetypes.guess_type('README'))  # → (None, None)
# Python 3.11+
import mimetypes
print(mimetypes.guess_type('https://ex.com/a.json?v=2'))  # → ('application/json', None)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy