Python Glossary Русский

Python 3.13+mimetypesfunction

mimetypes.guess_file_type()

guessing the type

Guesses the MIME type and compression from a file path (str or Path). The variant of guess_type meant for paths rather than URLs.

Syntax

mimetype, encoding = mimetypes.guess_file_type(path, *, strict=True)

guess_type parses its argument as a URL, so '#' and '?' in a file name are taken as the start of a fragment or query, and on Windows a path like C:\x.txt can be mistaken for a scheme. guess_file_type treats the argument purely as a path and avoids those surprises. Like guess_type, it only looks at the extension and never opens the file.

Examples

import mimetypes
from pathlib import Path
print(mimetypes.guess_file_type(Path('docs/report.txt')))  # → ('text/plain', None)
print(mimetypes.guess_file_type('data.json'))  # → ('application/json', None)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy