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