分享一个批量修改文件编码的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()

 

转载于:https://www.cnblogs.com/daimadebanyungong/p/11436286.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值