`

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):
#把文件由GBK编码转换为UTF-8编码,也就是filepath的编码是GBK
    convertEncoding("GBK", "UTF-8", filepath, filepath+".bak")

def convertFromUTF82gbk(filepath):
#把文件由UTF-8编码转换为GBK编码,也就是filepath的编码是UTF-8
    convertEncoding("UTF-8", "GBK", filepath, filepath+".bak")
 
filepath="e:\\test\\test5.txt"
convertFromUTF82gbk(filepath)

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics