Python (Scripting) - Determine file MIME type

by
Jeremy Canfield |
Updated: November 06 2023
| Python (Scripting) articles
The mimetypes module can be used to determine a files MIME type.
#!/usr/bin/python3
import mimetypes
filetype = mimetypes.MimeTypes().guess_type('/path/to/example.png')
print(f"example.pdf MIME type = {filetype}")
filetype = mimetypes.MimeTypes().guess_type('/path/to/example.pdf')
print(f"example.pdf MIME type = {filetype}")
In this example, the following should be returned.
example.png MIME type = ('image/png', None)
example.pdf MIME type = ('application/pdf', None)
Or better yet, return index 0 to just get the MIME type.
#!/usr/bin/python3
import mimetypes
filetype = mimetypes.MimeTypes().guess_type('/path/to/example.png')
print(f"example.png MIME type = {filetype[0]}")
filetype = mimetypes.MimeTypes().guess_type('/path/to/example.pdf')
print(f"example.pdf MIME type = {filetype[0]}")
Which should now return the following.
example.png MIME type = 'image/png'
example.pdf MIME type = 'application/pdf'
Or, using the magic module. To use the magic module, you will need to install the python-magic packages.
pip install python-magic
Then do something like this to return the MIME type.
#!/usr/bin/python3
import magic
mime = magic.Magic(mime=True)
mimetype = mime.from_file('/path/to/example.png')
print(f"example.png MIME type = {mimetype}")
mimetype = mime.from_file('/path/to/example.pdf')
print(f"example.pdf MIME type = {mimetype}")
Which should now return the following.
example.png MIME type = image/png
example.pdf MIME type = application/pdf
Did you find this article helpful?
If so, consider buying me a coffee over at