Python uses the file header to determine the file type,
For servers that provide upload, You need to filter uploaded files.
This article provides you with python's method of determining the file type through the file header to avoid unnecessary troubles.
The sharing code is as follows:
Import struct # supported file types # The purpose of using a hexadecimal string is to know how many bytes the file header is # The length of various file headers is different, with less than half 2 characters, the length is 8 characters. def typeList (): return {"52617221": EXT_RAR, "504B0304": EXT_ZIP} # convert the bytecode to a hexadecimal 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 () # obtain the file type def filetype (filename): binfile = open (filename, 'rb') # Read tl = typeList () ftype = 'unknown 'for hcode in tl. keys (): numOfBytes = len (hcode)/2 # number of bytes of binfile to be read. seek (0) # Return to the file header for each read, otherwise it will continue to read hbytes = struct. unpack_from ("B" * numOfBytes, binfile. read (numOfBytes) # A "B" indicates a 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)
Common file formats
File Format File Header (hexadecimal)
JPEG (jpg)FFD8FF
PNG (png)89504E47
GIF)47494638
TIFF (tif)4910000a00
Windows Bitmap (bmp)Mongod
CAD (dwg)41433130
Adobe Photoshop (psd)38425053
Rich Text Format (rtf)7B5C727466
XML (xml)3C3F786D6C
HTML (html)68746D6C3E
Email [thorough only] (eml)44656c69766572792d646172133a
Outlook Express (dbx)CFAD12FEC5FD746F
Outlook (pst)2142444E
MS Word/Excel (xls.or.doc)D0CF11E0
MS Access (mdb)5374616e64617213204a
The above is all the content of this article, hoping to help you learn.