Python to determine the type of upload file

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

123456789101112131415161718192021222324252627282930313233343536373839 importstruct # 支持文件类型 # 用16进制字符串的目的是可以知道文件头是多少字节 # 各种文件头的长度不一样,少半2字符,长则8字符 deftypeList():   return    "52617221": EXT_RAR,     "504B0304": EXT_ZIP}  # 字节码转16进制字符串 defbytes2hex(bytes):   num =len(bytes)   hexstr =u""   forinrange(num):     =u"%x"% bytes[i]     iflen(t) %2      hexstr +=u"0"    hexstr +=  returnhexstr.upper()  # 获取文件类型 deffiletype(filename):   binfile =open(filename, ‘rb‘# 必需二制字读取   tl =typeList()   ftype =‘unknown‘  forhcode in tl.keys():     numOfBytes =len(hcode) /2# 需要读多少字节     binfile.seek(0# 每次读取都要回到文件头,不然会一直往后读取     hbytes =struct.unpack_from("B"*numOfBytes, binfile.read(numOfBytes)) # 一个 "B"表示一个字节     f_hcode =bytes2hex(hbytes)     if f_hcode ==hcode:       ftype =tl[hcode]       break  #不要忘记关闭打开的文件,避免出现异常  binfile.close()   returnftype if__name__ ==‘__main__‘  printfiletype(‘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

Python to determine the type of upload file

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.