欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python批量修改文件編碼格式的方法

 更新時(shí)間:2018年05月31日 10:14:12   作者:vagerant  
這篇文章主要為大家詳細(xì)介紹了python批量修改文件編碼格式的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了python批量修改文件編碼格式的具體代碼,供大家參考,具體內(nèi)容如下

使用說(shuō)明:

1、使用工具:Python2.7.6+chardet2.3.0,chardet2.3.0下載地址:點(diǎn)擊這里

2、環(huán)境配置:Python安裝+配置環(huán)境變量,chardet解壓放在Python安裝目錄\Lib\site-packages下

舉例:批量修改當(dāng)前路徑下所有.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() 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論