分享一個批量修改文件編碼的python腳本


分享一個自己編寫的遞歸查找子目錄,將所有cpp文件編碼修改為utf-8編碼格式的小腳本

 

 1 #i!/usr/bin/env python3
 2 # -*- coding:utf-8 -*-
 3 import os 
 4 import sys 
 5 import codecs 
 6 import chardet 
 7   
 8 def convert(filename,out_enc="UTF-8"): 
 9   try: 
10     content=codecs.open(filename,'rb').read()
11     source_encoding=chardet.detect(content)['encoding'] 
12     print ("fileencoding:%s" % source_encoding)
13 
14     if source_encoding != None :
15       content=content.decode(source_encoding).encode(out_enc) 
16       codecs.open(filename,'wb').write(content)
17       content.close()
18     else :
19       print("can not recgonize file encoding %s" % filename)
20   except IOError as err: 
21     print("I/O error:{0}".format(err)) 
22   
23 def explore(dir): 
24   for root,dirs,files in os.walk(dir): 
25     for file in files: 
26       if os.path.splitext(file)[1]=='.cpp': 
27         print ("fileName:%s" % file)
28         path=os.path.join(root,file)
29         convert(path) 
30   
31 def main(): 
32   #explore(os.getcwd()) 
33   filePath = input("please input dir: \n")
34   explore(filePath)
35   
36 if __name__=="__main__": 
37   main()

 


免責聲明!

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



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