1. 程式人生 > >資料夾下所有utf8檔案轉ANSI檔案

資料夾下所有utf8檔案轉ANSI檔案

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!"

注: 轉載請註明出處