参考:http://blog.csdn.net/vagerant/article/details/50350171
#!/usr/bin/python
#-*-coding:utf-8-*-
import os
import sys
import codecs
import chardet
def convert(filename, out_enc="UTF-8"):
try:
# codecs.open()这个方法打开的文件读取返回的将是unicode。
content=codecs.open(filename,'r').read()
#chardet.detect 获取编码格式
source_encoding=chardet.detect(content)['encoding']
if None != source_encoding: #空的文件,返回None
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, source_encoding_list):
for root,dirs,files in os.walk(dir):
for file in files:
#os.path.splitext(path) 分割路径,返回路径名和文件扩展名的元组
if os.path.splitext(file)[1] in source_encoding_list:
path=os.path.join(root,file)
convert(path)
def main():
explore(os.getcwd(), [".cpp", ".h"])
if __name__=="__main__":
main()