Python通过文件头来判断文件的真实类型

来源:互联网 发布:资料器械进销存软件 编辑:程序博客网 时间:2024/06/04 19:29
分类: python 工具
 2838人阅读 评论(3) 收藏 举报
  1. ###  
  2. # 文章:Python通过文件头来判断文件类型  
  3. # 作者:http://aminby.net  
  4. ###  
  5.   
  6. import struct  
  7.   
  8. # 支持文件类型  
  9. # 用16进制字符串的目的是可以知道文件头是多少字节  
  10. # 各种文件头的长度不一样,少半2字符,长则8字符  
  11. def typeList():  
  12.     return {  
  13.         "52617221": EXT_RAR,  
  14.         "504B0304": EXT_ZIP}  
  15.   
  16. # 字节码转16进制字符串  
  17. def bytes2hex(bytes):  
  18.     num = len(bytes)  
  19.     hexstr = u""  
  20.     for i in range(num):  
  21.         t = u"%x" % bytes[i]  
  22.         if len(t) % 2:  
  23.             hexstr += u"0"  
  24.         hexstr += t  
  25.     return hexstr.upper()  
  26.   
  27. # 获取文件类型  
  28. def filetype(filename):  
  29.     binfile = open(filename, 'rb'# 必需二制字读取  
  30.     tl = typeList()  
  31.     ftype = 'unknown'  
  32.     for hcode in tl.keys():  
  33.         numOfBytes = len(hcode) / 2 # 需要读多少字节  
  34.         binfile.seek(0# 每次读取都要回到文件头,不然会一直往后读取  
  35.         hbytes = struct.unpack_from("B"*numOfBytes, binfile.read(numOfBytes)) # 一个 "B"表示一个字节  
  36.         f_hcode = bytes2hex(hbytes)  
  37.         if f_hcode == hcode:  
  38.             ftype = tl[hcode]  
  39.             break  
  40.     binfile.close()  
  41.     return ftype  
  42.   
  43. if __name__ == '__main__':  
  44.     print filetype(Your-file-path)  

常见文件格式的文件头

文件格式文件头(十六进制)JPEG (jpg)FFD8FFPNG (png)89504E47GIF (gif)47494638TIFF (tif)49492A00Windows Bitmap (bmp)424DCAD (dwg)41433130Adobe Photoshop (psd)38425053Rich Text Format (rtf)7B5C727466XML (xml)3C3F786D6CHTML (html)68746D6C3EEmail [thorough only] (eml)44656C69766572792D646174653AOutlook Express (dbx)CFAD12FEC5FD746FOutlook (pst)2142444EMS Word/Excel (xls.or.doc)D0CF11E0MS Access (mdb)5374616E64617264204AWordPerfect (wpd)FF575043Postscript (eps.or.ps)252150532D41646F6265Adobe Acrobat (pdf)255044462D312EQuicken (qdf)AC9EBD8FWindows Password (pwl)E3828596ZIP Archive (zip)504B0304RAR Archive (rar)52617221Wave (wav)57415645AVI (avi)41564920Real Audio (ram)2E7261FDReal Media (rm)2E524D46MPEG (mpg)000001BAMPEG (mpg)000001B3Quicktime (mov)6D6F6F76Windows Media (asf)3026B2758E66CF11MIDI (mid)4D546864

这种方法也可以在网络服务方法可以用来防止上传者来者修改扩展名来欺骗服务器干坏事。

转自:http://aminby.net/2013/07/python-file-header-recoginze-type-extension/
0 0
原创粉丝点击