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

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

    @toivotuo 's method worked best and most reliably for me under python3. My goal was to identify gzipped files which do not have a reliable .gz extension. I installed python3-magic.

    import magic
    
    filename = "./datasets/test"
    
    def file_mime_type(filename):
        m = magic.open(magic.MAGIC_MIME)
        m.load()
        return(m.file(filename))
    
    print(file_mime_type(filename))
    

    for a gzipped file it returns: application/gzip; charset=binary

    for an unzipped txt file (iostat data): text/plain; charset=us-ascii

    for a tar file: application/x-tar; charset=binary

    for a bz2 file: application/x-bzip2; charset=binary

    and last but not least for me a .zip file: application/zip; charset=binary

提交回复
热议问题