2023年 1月 25日

Python 改变文件编码格式

#-*- coding:UTF-8 -*-
import sys
import os
import codecs

def ReadFile(filePath,encoding):
    with codecs.open(filePath,'r',encoding) as f:
        return f.read()

def WriteFile(filePath,u,encoding):
    with codecs.open(filePath,"w",encoding) as f:
        f.write(u)

def GB2312_2_UTF8(src,dst):
    content = ReadFile(src,encoding="GB2312")
    WriteFile(dst,content,encoding="utf-8")

save_dir = 'D:\\QtParseXML\\pro file\\AfterConvert\\'

if __name__ == '__main__':
    SrcSet = "D:\QtParseXML\pro file\pro.txt"
    file_object = open(SrcSet,'r')
    for line in file_object.readlines():
#        line = line.decode('GBK')
        line = line.strip('\n')
        filename = line.split("\\")[-1]
        savePath = save_dir + filename
        print savePath
        GB2312_2_UTF8(line,savePath)
    file_object.closed