python准確判斷文件類型


判斷文件類型在開發中非常常見的需求,怎樣才能准確的判斷文件類型呢?首先大家想到的是文件的后綴,但是非常遺憾的是這種方法是非常不靠譜的,因為文件的后綴是可以隨意更改的,而大家都知道后綴在linux系統下是沒有這個概念的,所以僅靠判斷后綴無法准確判斷一個文件的類型。還有第二種方法是判斷文件的頭,每種文件在文件的頭中會標識這種文件的類型,下面我們來看看如何用python來判斷文件的類型。

python通過文件頭判斷文件類型的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#! /usr/bin/python
# pythontab提醒您注意中文編碼問題,指定編碼為utf-8
# -*- coding: utf-8 -*- 
import  struct
# 支持文件類型 
# 用16進制字符串的目的是可以知道文件頭是多少字節 
# 各種文件頭的長度不一樣,少則2字符,長則8字符 
def  typeList(): 
   return 
     "FFD8FF" "JPEG"
     "89504E47" "PNG"
    
# 字節碼轉16進制字符串 
def  bytes2hex(bytes): 
   num  =  len (bytes) 
   hexstr  =  u"" 
   for  in  range (num): 
     =  u "%x"  %  bytes[i] 
     if  len (t)  %  2
       hexstr  + =  u "0"
     hexstr  + = 
   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( './test.jpg' )

  

常見文件格式的文件頭

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
文件格式 文件頭(十六進制)
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

http://www.qytang.com/
http://www.qytang.com/cn/list/41/
http://www.qytang.com/cn/list/37/
http://www.qytang.com/cn/list/46/
http://www.qytang.com/cn/page/19.htm
http://www.qytang.com/cn/list/32/
http://www.qytang.com/cn/list/28/
http://www.qytang.com/cn/list/25/
http://www.qytang.com/cn/list/28/625.htm
http://www.qytang.com/cn/list/28/612.htm
http://www.qytang.com/cn/list/28/611.htm
http://www.qytang.com/cn/list/28/610.htm

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM