How to get the mime of a file through Python?

4

How can I get Mimetype from a file via Python?

I'm not just talking about getting through the extension, but also reading the file metadata.

How can I do this?

Note : I tried to use python-magic on Windows but it did not work.

    
asked by anonymous 27.06.2017 / 15:05

3 answers

1

Solution with Python-magic :

import magic
m = magic.Magic(mime=True)
mime_type = m.from_file("arquivo.pdf")
print mime_type

Edit:

According to the official website of the Python-magic library, there are 2 factors that could cause the above code to not work.

The first factor is a library name conflict because there are two libraries called magic for Python! The correct library would be Python-magic-0.4.13 .

The second factor (which may cause non-functioning in Windows) are the dependencies that need to be installed.

On Windows, the file vice utility must exist on the machine and its path must be passed as an argument to the constructor:

import magic
m = magic.Magic(magic_file="C:\windows\system32\file.exe")
mime_type = m.from_file("arquivo.pdf")
print mime_type

The% compiled% utility for Windows can be obtained here .

More details can be found here .

    
27.06.2017 / 20:33
0

shlex:

import subprocess
import shlex

file_name = 'pdf.fake'
cmd = shlex.split('file --mime-type {0}'.format(file_name))
result = subprocess.check_output(cmd)
mime_type = result.split()[-1]
print (mime_type)

Output:

b'application/pdf'
    
27.06.2017 / 17:18
0

You can use the mimetypes library:

>>> import urllib, mimetypes
>>> 
>>> url = urllib.pathname2url('meu_arquivo.xml')
>>> print mimetypes.guess_type(url)
('application/xml', None)

Reference: link

    
27.06.2017 / 19:29