How to get the MIME type of a file in Python. By doing this, you can change the behavior by judging the format of the input file.
import mimetypes
mime = mimetypes.guess_type(File path)
print(mime) # => (MIME type,Encode format)
That's it. In the encoding format part, if it is a file compressed with gzip, some value will appear, but basically it will be None.
As a simple example, let's say you only accept Markdown files. If any other file is entered, an error message will be displayed.
markdown.py
import mimetypes
import sys
input = sys.argv[1]
mime = mimetypes.guess_type(input)
if mime[0] = "text/markdown":
print("You're a Markdown file!")
else:
print("{mime}Type of file is over there!".format(mime=mime[0]))
When you run ...
$ python3 markdown.py hoge.md
You're a Markdown file!
$ python3 markdown.py fuga.jpg
image/jpeg type files are sick!
Recommended Posts