python xml文件读取和转换有关问题

【求助】python xml文件读取和转换问题#将GB2312格式转为UTF-8格式f codecs.open(e:\TestResult.xml, r

【求助】python xml文件读取和转换问题
#将GB2312格式转为UTF-8格式
  f = codecs.open('e:\TestResult.xml', "rb", "gb2312")
  text = f.read().encode("utf-8")  
  f.close
  f = open(options.TestResultFile, "wb")  
  f.write(text)  
  f.close()  

提示 File "E:\TOOLS\ICP\ICP-23\cruisecontrol\userData\groups\group01\projects\R12ProductTest\script\pyt
hon_script\StaticResult.py", line 29, in main
  text = f.read().encode("utf-8")  
  File "C:\Python25\lib\codecs.py", line 606, in read
  return self.reader.read(size)
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 55-56: illegal multibyte sequence

是f.read()出了问题,因为。encode("utf-8") 去掉仍然是该现象。

不知道我这里读取有何问题?

这是成熟的产品代码,已经有别人在使用。而且我使用他们同样的文件来操作,以及同样的python版本(2.5)也是这样的问题,好奇怪!

[解决办法]
试试改gbk范围比gb2312大。codecs好像是python基本模块,真的有问题的话大家的都一样要错的吧...
下面是wingdows下官版shell里一个简单测试,gbk能而gb2312不能:

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '\x81\x40'
>>> print s

>>> s.decode('gbk')
u'\u4e02'
>>> s.decode('gb2312')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 0-1: illegal m
ultibyte sequence
>>>
[解决办法]
我是这样转的

Python code
    def open(self, xmlfile):        returnStatus = False        try:            data = self._openAnything(xmlfile)            if data:                data = data.decode('GBK').encode('UTF-8')                data = data.replace('gb2312', 'utf-8')                data = data.replace('GB2312', 'utf-8')                self.__xmldom = xml.dom.minidom.parseString(data)                self.__isOpenFile = True                returnStatus = True        except Exception, e:            print Exception, e            returnStatus = False        return returnStatus