欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 转换文件编码 博客分类: python python文件编码改变文件编码编码格式 

程序员文章站 2024-02-24 20:51:34
...
'''
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)