Python determines file type by file header

Source: Internet
Author: User
For the server that provides the upload, the uploaded file needs to be filtered.

This article provides a way for Python to determine file types through the file header, avoiding unnecessary hassles.

Share the code below

Import struct  # support file type # with 16 binary string is the purpose is to know the file header is how many bytes # various file header length is not the same, less half 2 characters long 8 characters def typelist ():   return {     " 52617221 ": Ext_rar,     " 504b0304 ": Ext_zip}  # Bytecode to 16 binary string def bytes2hex (bytes):   num = len (bytes)   hexstr = U "" for   I in range (num):     t = u "%x"% bytes[i]     if Len (t)% 2:       hexstr + = u "0"     hexstr + = t   return Hexstr.upper ()  # Gets the file type def filetype (filename):   binfile = open (filename, ' RB ') # required binary word read   TL = typelist () C16/>ftype = ' unknown ' for   Hcode in Tl.keys ():     numofbytes = Len (hcode)/2 # required to read how many bytes     binfile.seek (0) # per read Go back to the file header, or you'll read it backwards.     hbytes = Struct.unpack_from ("b" *numofbytes, Binfile.read (numofbytes)) # a "B" means one byte     f_ Hcode = Bytes2hex (hbytes)     if F_hcode = = Hcode:       ftype = Tl[hcode] Break   binfile.close ()   Return ftype  If __name__ = = ' __main__ ':   print filetype (your-file-path)

File headers for common file formats

file Format file header (hex)
JPEG (jpg)Ffd8ff
PNG (PNG)89504E47
gif (GIF)47494638
TIFF (TIF)49492a00
Windows Bitmap (BMP)424D
CAD (DWG)41433130
Adobe Photoshop (PSD)38425053
Rich Text Format (RTF)7b5c727466
XML (XML)3c3f786d6c
HTML (HTML)68746d6c3e
Email [Thorough only] (EML)44656c69766572792d646174653a
Outlook Express (dbx)cfad12fec5fd746f
Outlook (PST)2142444E
MS word/excel (xls.or.doc)D0cf11e0
MS Access (MDB)5374616e64617264204a

The above is the whole content of this article, I hope that everyone's study has helped.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.