import codecs
import chardet
import sys
reload(sys)
sys.setdefaultencoding('utf-8') #如果没有这部分,WriteFile会报错
def RedaFile(filename,encoding="utf-8"):
with codecs.open(filename,"r") as f:
content = f.read()
f.close()
if chardet.detect(content)["encoding"] == encoding: #只转utf8编码的
return content
else:
return None
def WriteFile(filename,content,encoding="gb18030"):
with codecs.open(filename,"wb",encoding) as f:
f.write(content)
f.close()
def utf8_to_ansi(src,dst):
content = RedaFile(src,encoding="utf-8")
if content:
WriteFile(dst,content,encoding="gb18030")
print "change file is %s"%dst
def FilesFormat(path):
for root, dirs, files in os.walk(path):
for f in files:
if f[-2:] == '.c' or f[-2:] == '.h': #只转.c和.h文件
utf8_to_ansi(root+"\\"+f, root+"\\"+f) #新文件覆盖旧文件
if __name__ == "__main__":
FilesFormat(r'D:\pt-ct-em_ansi') #文件夹目录
print "ALL FILES DONE!"
注: 转载请注明出处