Ignacio mentioned the Magic library, but you can also do this with the standard library if you are sure that the file name is enough to find out the file type (by extension):
>>> import mimetypes >>> mimetypes.guess_type('__init__.py') ('text/x-python', None)
See the Mimetypes module in the standard library. This, however, is not a substitute for actually controlling the contents of a file and determining its type.
source share