天天看點

python 轉換檔案編碼

python 轉換檔案編碼

''''' 

created on 2013-2-26 

@author: whuang 

'''  

def convertencoding(from_encode,to_encode,old_filepath,target_file):  

    f1=file(old_filepath)  

    content2=[]  

    while true:  

        line=f1.readline()  

#        print line  

        content2.append(line.decode(from_encode).encode(to_encode))  

        if len(line) ==0:  

            break  

    f1.close()  

#    print line  

    f2=file(target_file,'w')  

    f2.writelines(content2)  

    f2.close()  

def convertfromgbk2utf8(filepath):  

<strong><span style="color: #ff0000;">#把檔案由gbk編碼轉換為utf-8編碼,也就是filepath的編碼是gbk</span></strong>  

    convertencoding("gbk", "utf-8", filepath, filepath+".bak")  

def convertfromutf82gbk(filepath):  

#<span style="color: #ff0000;"><strong>把檔案由utf-8編碼轉換為gbk編碼,也就是filepath的編碼是utf-8</strong></span>  

    convertencoding("utf-8", "gbk", filepath, filepath+".bak")  

filepath="e:\\test\\test5.txt"  

convertfromutf82gbk(filepath)