Detailed Python judgment upload file type

Source: Internet
Author: User
In the development of uploading services, it is often necessary to filter the uploaded files.

This article provides a way for Python to determine file types by file header, which is very useful.

The code is as follows

Import struct # support file type # with 16 binary string to be able to know the file header is how many bytes # various file header length is not the same, less than 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.up Per ()  # Gets the file type def filetype (filename):   binfile = open (filename, ' RB ') # required binary word read   TL = typelist ()   Ftype = ' unknown ' for   Hcode in Tl.keys ():     numofbytes = Len (hcode)/2 # Number of bytes needed to read     Binfile.seek (0) # Every time I read it back to the text header, or it will be read backwards     hbytes = Struct.unpack_from ("b" *numofbytes, Binfile.read (numofbytes)) # a "B" means a byte     F_hcode = Bytes2hex (hbytes)     if F_hcode = = Hcode:       ftype = Tl[hcode] Break  #不要忘记关闭打开的文件 to avoid exceptions  Binfile.close ()   return ftype if __name__ = = ' __main__ ':   print filetype (' pythontab.jpg ')

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

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.