Python處理utf-8 添加和刪除BOM頭


以下代碼只處理了assic和utf8文件。其它文件編碼為保險起見並未加入支持。
參數
exts 需要處理文件的擴展名
folders 需要處理的文件夾及子目錄
處理目錄為當前目錄
運行:
添加bom頭
python proc_bom.py
刪除bom頭
python proc_bom.py -r

運行缺少chardet報錯 

方法1:在線安裝

  pip install chardet

方法2:離線安裝

https://github.com/chardet/chardet

https://pypi.python.org/pypi/chardet#downloads

去下載chardet包

進入到chardet 3.0.4 的解壓包里,執行:python setup.py install 就可以完成安裝了。

 

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 
 4 import os;
 5 import sys;
 6 import codecs;
 7 import chardet;
 8 
 9 #獲取腳本文件的當前路徑
10 def cur_file_dir():
11      #獲取腳本路徑
12      path = sys.path[0]
13      #判斷為腳本文件還是py2exe編譯后的文件,如果是腳本文件,則返回的是腳本的目錄,如果是py2exe編譯后的文件,則返回的是編譯后的文件路徑
14      if os.path.isdir(path):
15          return path
16      elif os.path.isfile(path):
17          return os.path.dirname(path)
18 #打印結果
19 
20 
21 #pip install chardet 安裝相應插件
22 def procBOM(strPath,curLen, bAdd):
23     newcontent = '';
24     f = open(strPath, "rb");
25     fcontent = f.read();
26     f.close();
27     printBuffer = strPath[curLen:]
28     codeType = chardet.detect(fcontent)["encoding"]  #檢測編碼方式  
29      printBuffer = printBuffer + "  "+str(codeType) 
30 
31      if codeType.lower().find('utf-8') == -1 and codeType.lower().find('ascii') == -1 :
32          #非utf8文件保險起見先退出,並輸出錯誤提示,todo后續再添加其它轉碼到utf8
33          print printBuffer + " error OK"
34          return
35     
36     #不需要轉換,已經添加bom頭    
37 
38     if bAdd and fcontent[:3] != codecs.BOM_UTF8:
39         print  printBuffer+" add bom",
40         newcontent = codecs.BOM_UTF8;
41         newcontent += fcontent;
42     elif not bAdd and fcontent[:3] == codecs.BOM_UTF8:
43         newcontent = fcontent[3:];
44         print  printBuffer+" del bom",
45     else:
46         return;
47     fnew = open(strPath, "wb+")
48     fnew.write(newcontent);
49     fnew.close();
50     print "done"
51     return
52 
53 if __name__ == "__main__":
54 
55     bAdd = True;
56     exts = ['.h', '.c', '.cpp'];
57     folders = ["GNaviInterface/search","src","tester"]
58     bAdd = True;
59     if(len(sys.argv) > 1 and sys.argv[1] == '-r'):
60         bAdd = False;
61     curLen = len(cur_file_dir())
62     for folderName in folders:
63         folderPath = cur_file_dir()+"/"+folderName+"/"
64         #print "procBOM:folder path = "+folderPath+",add = "+str(bAdd)
65         for parent,dirnames,filenames in os.walk(folderPath):
66             for f in filenames:
67                 bTargetFile = False;
68                 for e in exts:
69                     if(f.endswith(e)):
70                         bTargetFile = True;
71                 if(bTargetFile):
72                     procBOM(os.path.join(parent,f),curLen, bAdd);
73 #print 'file:%s add:%s' % (os.path.join(parent, f), bAdd);

 


免責聲明!

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



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