首页 > Python:如何使用codecs模块将unicode数据保存成gbk格式

Python:如何使用codecs模块将unicode数据保存成gbk格式

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

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

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

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

#coding:utf-8
import os
import codecs

def 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 None

def WriteFile(filePath,u,encoding="gb2312"):
    try:
        f = codecs.open(filePath,"w",encoding)
        f.writelines(u)
        f.flush()
        f.close()
    except Exception,ex:
        pass

def UTF8_2_GBK(src,dst):
    try:
        content = ReadFile(src,encoding="utf-8")
        WriteFile(dst,content,"gb2312")
    except Exception,ex:
        pass


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

  1. ReadFile 返回的是字符串,但是你在 WriteFile 里把它当列表了
  2. 明明有 .read() 方法一次读取整个文件内容、.readlines() 作为行的列表读入,为什么不用?
  3. 没事别学一些不会编程的 Javaers,不要抓你不知道如何处理的异常。难道你不小心写错了语法你不希望它直接告诉你,而喜欢错误和你玩捉迷藏吗
python#coding:utf-8

import os
import codecs

def 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")
【热门文章】
【热门文章】