欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python通過文件頭判斷文件類型

 更新時間:2015年10月30日 15:46:31   投稿:lijiao  
這篇文章主要介紹了python通過文件頭判斷文件類型,需要的朋友可以參考下

對于提供上傳的服務(wù)器,需要對上傳的文件進(jìn)行過濾。

本文為大家提供了python通過文件頭判斷文件類型的方法,避免不必要的麻煩。

分享代碼如下

import struct 
 
# 支持文件類型 
# 用16進(jìn)制字符串的目的是可以知道文件頭是多少字節(jié) 
# 各種文件頭的長度不一樣,少半2字符,長則8字符 
def typeList(): 
  return { 
    "52617221": EXT_RAR, 
    "504B0304": EXT_ZIP} 
 
# 字節(jié)碼轉(zhuǎn)16進(jìn)制字符串 
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 # 需要讀多少字節(jié) 
    binfile.seek(0) # 每次讀取都要回到文件頭,不然會一直往后讀取 
    hbytes = struct.unpack_from("B"*numOfBytes, binfile.read(numOfBytes)) # 一個 "B"表示一個字節(jié) 
    f_hcode = bytes2hex(hbytes) 
    if f_hcode == hcode: 
      ftype = tl[hcode] 
      break 
  binfile.close() 
  return ftype 
 
if __name__ == '__main__': 
  print filetype(Your-file-path)

常見文件格式的文件頭

文件格式 文件頭(十六進(jìn)制)
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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評論