How to find the mime type of a file in python?

前端 未结 19 1156
猫巷女王i
猫巷女王i 2020-11-22 15:19

Let\'s say you want to save a bunch of files somewhere, for instance in BLOBs. Let\'s say you want to dish these files out via a web page and have the client automatically o

19条回答
  •  醉梦人生
    2020-11-22 15:48

    Python bindings to libmagic

    All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a short answer listing the available option.

    libmagic

    • module name: magic
    • pypi: file-magic
    • source: https://github.com/file/file/tree/master/python

    When determining a files mime-type, the tool of choice is simply called file and its back-end is called libmagic. (See the Project home page.) The project is developed in a private cvs-repository, but there is a read-only git mirror on github.

    Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called file-magic. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: man libmagic. The basic usage is described in the readme file:

    import magic
    
    detected = magic.detect_from_filename('magic.py')
    print 'Detected MIME type: {}'.format(detected.mime_type)
    print 'Detected encoding: {}'.format(detected.encoding)
    print 'Detected file type name: {}'.format(detected.name)
    

    Apart from this, you can also use the library by creating a Magic object using magic.open(flags) as shown in the example file.

    Both toivotuo and ewr2san use these file-magic bindings included in the file tool. They mistakenly assume, they are using the python-magic package. This seems to indicate, that if both file and python-magic are installed, the python module magic refers to the former one.

    python-magic

    • module name: magic
    • pypi: python-magic
    • source: https://github.com/ahupp/python-magic

    This is the library that Simon Zimmermann talks about in his answer and which is also employed by Claude COULOMBE as well as Gringo Suave.

    filemagic

    • module name: magic
    • pypi: filemagic
    • source: https://github.com/aliles/filemagic

    Note: This project was last updated in 2013!

    Due to being based on the same c-api, this library has some similarity with file-magic included in libmagic. It is only mentioned by mammadori and no other answer employs it.

提交回复
热议问题