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

前端 未结 19 929
猫巷女王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:32

    The python-magic method suggested by toivotuo is outdated. Python-magic's current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.

    # For MIME types
    import magic
    mime = magic.Magic(mime=True)
    mime.from_file("testdata/test.pdf") # 'application/pdf'
    
    0 讨论(0)
  • 2020-11-22 15:36

    in python 2.6:

    mime = subprocess.Popen("/usr/bin/file --mime PATH", shell=True, \
        stdout=subprocess.PIPE).communicate()[0]
    
    0 讨论(0)
  • 2020-11-22 15:36

    I try mimetypes library first. If it's not working, I use python-magic libary instead.

    import mimetypes
    def guess_type(filename, buffer=None):
    mimetype, encoding = mimetypes.guess_type(filename)
    if mimetype is None:
        try:
            import magic
            if buffer:
                mimetype = magic.from_buffer(buffer, mime=True)
            else:
                mimetype = magic.from_file(filename, mime=True)
        except ImportError:
            pass
    return mimetype
    
    0 讨论(0)
  • 2020-11-22 15:37

    you can use imghdr Python module.

    0 讨论(0)
  • 2020-11-22 15:39

    The mimetypes module in the standard library will determine/guess the MIME type from a file extension.

    If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the UploadedFile object.

    0 讨论(0)
  • 2020-11-22 15:39

    There are 3 different libraries that wraps libmagic.

    2 of them are available on pypi (so pip install will work):

    • filemagic
    • python-magic

    And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution.

    In Debian the package python-magic is about this one and it is used as toivotuo said and it is not obsoleted as Simon Zimmermann said (IMHO).

    It seems to me another take (by the original author of libmagic).

    Too bad is not available directly on pypi.

    0 讨论(0)
提交回复
热议问题