4

Why do some files not have mimetypes?

guess_type returns a tuple with information about the file type like 'image/jpeg', 'application/xml', 'text/plain' , ....

Why do other files return no information 'None' even though the file exits and is not empty?

>> import mimetypes
>> mimetypes.guess_type('myfile.xx')
jtlz2
  • 7,700
  • 9
  • 64
  • 114
Lou.rn
  • 85
  • 2
  • 6

2 Answers2

5

(Answered here: How to find the mime type of a file in python?)


The how

Do this:

>>> pip install python-magic
>>> import magic
>>> mime = magic.Magic(mime=True)
>>> mime.from_file("testdata/test.pdf")

The why

The "mimetypes" library isn't very good, (it's unreliable). The "none" is that the specified file isn't recognized as a known filetype, (an extension don't a fileype make).


Hope this solves your issue and answers your question

Frank R. Haugen
  • 210
  • 3
  • 11
  • 1
    For me, I first got "raise ImportError('failed to find libmagic. Check your installation')" So, it should be noted that you have to first install "libmagic". I'm on a Mac, so `sudo port install libmagic` took care of that. However, this solution still incorrectly gave me back "application/octet-stream", when exiftool gave me "MIME Type : video/x-dv", which is correct. As noted, "mimetypes" also unreliably gave me back "None". – LOlliffe Nov 06 '19 at 23:17
2

You can install the package with pip install filemime and use it as follows. all type of files find file type and mime type filemime

from filemime import filemime

fileObj = filemime()
val = fileObj.load_file("Kodi_Kodi.mp3")
print(f"file: {val}")

mime = fileObj.load_file("Kodi_Kodi.mp3",mimeType=True)
print(f"mime-type: {mime}")

output:

file: 'Audio file with ID3 version 2.3.0, contains:MPEG ADTS, layer III, v1, 160 kbps, 44.1 kHz, Stereo'
mime-type: 'audio/mpeg'
THAVASI.T
  • 131
  • 1
  • 5