python批量修改文件编码格式的方法

我之所以要赞美你,更重要的是因为:你还哺育春天的的摇篮。 "冬天来了,春天还会远吗? "在冬天里,思想被提纯了,一直被坚定了,力量在储蓄着。一旦春风拂面,一切更争先恐后,生气勃勃,万紫千红,千姿百态。仿佛含苞的花蕾忽然绽开。

本文实例为大家分享了python批量修改文件编码格式的具体代码,供大家参考,具体内容如下

使用说明:

1、使用工具:Python2.7.6+chardet2.3.0,chardet2.3.0下载地址:点击这里

2、环境配置:Python安装+配置环境变量,chardet解压放在Python安装目录\Lib\site-packages下

举例:批量修改当前路径下所有.cpp文件的编码格式为UTF-8,代码如下:

python:

import os 
import sys 
import codecs 
import chardet 
 
def convert(filename,out_enc="UTF-8"): 
  try: 
    content=codecs.open(filename,'r').read() 
    source_encoding=chardet.detect(content)['encoding'] 
    print source_encoding 
 
    content=content.decode(source_encoding).encode(out_enc) 
    codecs.open(filename,'w').write(content) 
  except IOError as err: 
    print("I/O error:{0}".format(err)) 
 
def explore(dir): 
  for root,dirs,files in os.walk(dir): 
    for file in files: 
      if os.path.splitext(file)[1]=='.cpp': 
        print file 
        path=os.path.join(root,file) 
        convert(path) 
 
def main(): 
  explore(os.getcwd()) 
 
if __name__=="__main__": 
  main() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战