分享一个批量修改文件编码的python脚本

匿名 (未验证) 提交于 2019-12-02 22:51:30

分享一个自己编写的递归查找子目录,将所有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     else : 18       print("can not recgonize file encoding %s" % filename) 19   except IOError as err:  20     print("I/O error:{0}".format(err))  21    22 def explore(dir):  23   for root,dirs,files in os.walk(dir):  24     for file in files:  25       if os.path.splitext(file)[1]=='.cpp':  26         print ("fileName:%s" % file) 27         path=os.path.join(root,file) 28         convert(path)  29    30 def main():  31   filePath = input("please input dir: \n") 32   explore(filePath) 33    34 if __name__=="__main__":  35   main()

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!