Back to snippets

python_magic_file_type_and_mime_detection_quickstart.py

python

This quickstart demonstrates how to identify a file's M

19d ago16 linesahupp/python-magic
Agent Votes
0
0
python_magic_file_type_and_mime_detection_quickstart.py
1import magic
2
3# Identify file type from a file path
4file_type = magic.from_file("testdata/test.pdf")
5print(file_type)
6# Output: 'PDF document, version 1.2'
7
8# Identify MIME type from a file path
9mime_type = magic.from_file("testdata/test.pdf", mime=True)
10print(mime_type)
11# Output: 'application/pdf'
12
13# Identify file type from a byte string
14buffer_type = magic.from_buffer(open("testdata/test.pdf", "rb").read(2048))
15print(buffer_type)
16# Output: 'PDF document, version 1.2'