本文实例为大家分享了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() 另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。