溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2020-09-24 07:16:55 來源:腳本之家 閱讀:285 作者:vagerant 欄目:開發(fā)技術(shù)

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

使用說明:

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

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() 

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI