python批量修改文件編碼格式的方法
更新時間:2018年05月31日 10:14:12 作者:vagerant
這篇文章主要為大家詳細介紹了python批量修改文件編碼格式的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python批量修改文件編碼格式的具體代碼,供大家參考,具體內(nèi)容如下
使用說明:
1、使用工具:Python2.7.6+chardet2.3.0,chardet2.3.0下載地址:點擊這里
2、環(huán)境配置:Python安裝+配置環(huán)境變量,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()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python?基本結(jié)構(gòu)語句(函數(shù)和模塊)
這篇文章主要介紹了python?基本結(jié)構(gòu)語句(函數(shù)和模塊),文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09