def ReadFile(filePath,encoding="utf-8"): with codecs.open(filePath,"r",encoding) as f: return f.read() def WriteFile(filePath,u,encoding="gbk"): with codecs.open(filePath,"w",encoding) as f: f.write(u) def UTF8_2_GBK(src,dst): content = ReadFile(src,encoding="utf-8") WriteFile(dst,content,encoding="gbk")
def UTF8_2_GBK(src,dst): content = ReadFile(src,encoding="utf-8") WriteFile(dst,content,encoding="gb18030")
運行後,發現沒有報錯,能夠正常運行。python
def WriteFile(filePath,u,encoding="gbk"): with codecs.open(filePath,"w") as f: f.write(u.encode(encoding,errors="ignore"))
這裏,咱們將Unicode編碼(encode)成gbk格式,可是注意encode函數的第二個參數,咱們賦值"ignore",表示在編碼的時候,忽略掉那些沒法編碼的字符,函數
def WriteFile(filePath,u,encoding="gbk"): with codecs.open(filePath,"wb") as f: f.write(u.encode(encoding,errors="ignore"))