Home >Backend Development >Python Tutorial >How to Discover File MIME Types in Python?

How to Discover File MIME Types in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 10:14:02769browse

How to Discover File MIME Types in Python?

Discovering File MIME Types in Python

Determining a file's MIME type is crucial for facilitating automatic opening in browsers based on content-type headers in HTTP responses. This article explores methods for obtaining MIME types in Python.

Using the python-magic Library

The python-magic library provides a straightforward approach to extracting MIME types. Its current trunk located at Github offers an updated method:

import magic
mime = magic.Magic(mime=True)
mime.from_file("testdata/test.pdf") # 'application/pdf'

This code snippet retrieves the MIME type of the file named "test.pdf," which in this case is "application/pdf."

Additional Considerations

  • Browser Involvement: Browsers do not generally add MIME type information when posting files.
  • Databases for MIME Types: While dedicated databases for MIME types exist, it's generally more efficient to use a library like python-magic.

The above is the detailed content of How to Discover File MIME Types in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn