Python codecs模块可以将unicode数据保存成gbk格式吗,codecsgbk,需求:使用codecs模


需求:使用codecs模块将utf-8的文件保存成gbk格式。

读取的时候,已经将编码设置成utf-8了。输出结果是unicode字符串。

但是在将unicode字符串写入文件并保存为gbk的时候,发现文件内容为空(0kb)。

注:测试的时候,发现有的文件转码的时候,文件变小了,而且内容被截断。
比如:原本a.txt的内容为:
<div><table> </table></div>
但转码后变成:<div><table>
原本以为是NUL字符的问题,但后面替换了NUL字符,发现结果还是一样。
python代码如下:

#coding:utf-8import osimport codecsdef ReadFile(filePath,encoding="utf-8"):    try:        strContent = ""        f = codecs.open(filePath,"r",encoding=encoding)        line = f.readline()        while(line):            strContent += line            line = f.readline()        f.close()        return strContent    except Exception,ex:        return Nonedef WriteFile(filePath,u,encoding="gb2312"):    try:        f = codecs.open(filePath,"w",encoding)        f.writelines(u)        f.flush()        f.close()    except Exception,ex:        passdef UTF8_2_GBK(src,dst):    try:        content = ReadFile(src,encoding="utf-8")        WriteFile(dst,content,"gb2312")    except Exception,ex:        pass

代码太 C-ish、Java-ish 了。从你忽略这么多异常来看,你根本就是找死:

python#coding:utf-8import osimport codecsdef ReadFile(filePath, encoding):    with codecs.open(filePath, "r", encoding=encoding) as f:        return f.read()def WriteFile(filePath, content, encoding):    with codecs.open(filePath, "w", encoding=encoding) as f:        f.write(content)def UTF8_to_GBK(src, dst):    content = ReadFile(src, encoding="utf-8")    WriteFile(dst, content, "gbk")

编橙之家文章,

评论关闭