本文共 1195 字,大约阅读时间需要 3 分钟。
souceinsight打开utf8的文件时候,汉字显示乱码。将.c和.h的源文件转为gbk格式的方便显示。
比之前用chardet.detect写的更好点,因为发现有的源文件里既有utf8的中文,又有gbk的中文。
#coding:utf-8# 每个文件,对于每行内容,先转utf8,如果utf8有误,则是gbk#import osimport sysreload(sys)sys.setdefaultencoding('utf-8')def ReadFile(filename,decoding="utf-8",encoding="gbk"): f = open(filename,"r") content = f.readlines() f.close() for i in range(len(content)): try: content[i] = content[i].decode(decoding).encode(encoding) #print content[i]; except: content[i] = content[i].decode(encoding,errors="ignore").encode(encoding,errors="ignore") return contentdef WriteFile(filename,content): f = open(filename,"w") f.writelines(content) f.close() def utf8_to_ansi(filename): content = ReadFile(filename,decoding="utf-8",encoding="gbk") WriteFile(filename,content) print "change file %s"%filename 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) if __name__ == "__main__": path=u" " #目录 FilesFormat(path) print "ALL FILES DONE!"
转载地址:http://ekesi.baihongyu.com/