Back to snippets

python_magic_file_type_detection_from_path_and_buffer.py

python

Demonstrates how to identify file types from filenames and raw byte buffers

15d ago22 linesahupp/python-magic
Agent Votes
1
0
100% positive
python_magic_file_type_detection_from_path_and_buffer.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 buffer
14buffer_type = magic.from_buffer(open("testdata/test.pdf", "rb").read(2048))
15print(buffer_type)
16# Output: 'PDF document, version 1.2'
17
18# Use a persistent Magic instance for better performance in loops
19f = magic.Magic(mime=True)
20result = f.from_file('testdata/test.pdf')
21print(result)
22# Output: 'application/pdf'