159. MIME Types with mimetypes
Here are 10 Python snippets demonstrating how to determine MIME types of files based on their extensions using the mimetypes library. Each snippet is separated by a delimiter.
Snippet 1: Determine MIME Type of a File
import mimetypes
file_path = 'example.txt'
mime_type, encoding = mimetypes.guess_type(file_path)
print(f"MIME type: {mime_type}, Encoding: {encoding}")Snippet 2: Determine MIME Type for Multiple Files
import mimetypes
file_paths = ['document.pdf', 'image.jpg', 'audio.mp3']
for file_path in file_paths:
mime_type, encoding = mimetypes.guess_type(file_path)
print(f"File: {file_path}, MIME type: {mime_type}")Snippet 3: Handling Unknown MIME Types
Snippet 4: Determine MIME Type of an Image File
Snippet 5: Determine MIME Type of a Video File
Snippet 6: Set MIME Type for Custom File Extensions
Snippet 7: Get MIME Type of an HTML File
Snippet 8: Determine MIME Type of a Compressed File
Snippet 9: Determine MIME Type Based on URL
Snippet 10: Guess MIME Type with Unknown Extension
Last updated