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!"
注: 转载请注明出处
本文介绍了一个使用Python编写的脚本,该脚本可以将指定文件夹内的.c和.h文件从UTF-8编码转换为GB18030编码。通过读取文件内容并检查其当前编码是否为UTF-8,如果是,则进行转换并覆盖原文件。

8441

被折叠的 条评论
为什么被折叠?



