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

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

提交回复
热议问题