源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

python通过文件头判断文件类型

  • 时间:2022-03-05 11:51 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:python通过文件头判断文件类型
对于提供上传的服务器,需要对上传的文件进行过滤。 本文为大家提供了python通过文件头判断文件类型的方法,避免不必要的麻烦。 分享代码如下
import struct 
 
# 支持文件类型 
# 用16进制字符串的目的是可以知道文件头是多少字节 
# 各种文件头的长度不一样,少半2字符,长则8字符 
def typeList(): 
  return { 
    "52617221": EXT_RAR, 
    "504B0304": EXT_ZIP} 
 
# 字节码转16进制字符串 
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() 
 
# 获取文件类型 
def filetype(filename): 
  binfile = open(filename, 'rb') # 必需二制字读取 
  tl = typeList() 
  ftype = 'unknown' 
  for hcode 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() 
  return ftype 
 
if __name__ == '__main__': 
  print filetype(Your-file-path)
常见文件格式的文件头 [b]文件格式 文件头(十六进制) [/b][b]JPEG (jpg) [/b]FFD8FF [b]PNG (png) [/b]89504E47 [b]GIF (gif)[/b] 47494638 [b]TIFF (tif) [/b]49492A00 [b]Windows Bitmap (bmp)[/b] 424D [b]CAD (dwg) [/b]41433130 [b]Adobe Photoshop (psd)[/b] 38425053 [b]Rich Text Format (rtf)[/b] 7B5C727466 [b]XML (xml) [/b]3C3F786D6C [b]HTML (html) [/b]68746D6C3E [b]Email [thorough only] (eml) [/b]44656C69766572792D646174653A [b]Outlook Express (dbx) [/b]CFAD12FEC5FD746F [b]Outlook (pst) [/b]2142444E [b]MS Word/Excel (xls.or.doc) [/b]D0CF11E0 [b]MS Access (mdb) [/b]5374616E64617264204A 以上就是本文的全部内容,希望对大家的学习有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部