Check if a file type is a media file?
There is another method that is based not on the file extension but on the file contents using the media type library pypi.org/project/python-libmagic:
Here is the sample code for this library:
import magic
magic = magic.Magic()
mimestart = magic.from_file("test.mp3").split('/')[0]
if mimestart in ['audio', 'video', 'image']:
print("media types")
NOTE: for using this code sample you need to install python-libmagic using pip.
For this purpose you need to get internet media type for file, split it by / character and check if it starts with audio,video,image.
Here is a sample code:
import mimetypes
mimetypes.init()
mimestart = mimetypes.guess_type("test.mp3")[0]
if mimestart != None:
mimestart = mimestart.split('/')[0]
if mimestart in ['audio', 'video', 'image']:
print("media types")
NOTE: This method assume the file type by its extension and don't open the actual file, it is based only on the file extension.
Creating a module
If you want to create a module that checks if the file is a media file you need to call the init function at the start of the module.
Here is an example of how to create the module:
ismediafile.py
import mimetypes
mimetypes.init()
def isMediaFile(fileName):
mimestart = mimetypes.guess_type(fileName)[0]
if mimestart != None:
mimestart = mimestart.split('/')[0]
if mimestart in ['audio', 'video', 'image']:
return True
return False
and there how to use it:
main.py
from ismediafile import isMediaFile
if __name__ == "__main__":
if isMediaFile("test.mp3"):
print("Media file")
else:
print("not media file")