2014-02-22 32 views
0
In [458]: type(obj_xml) 
Out[458]: builtins.bytes 

In [459]: with codecs.open(xmlOutFile, "+ab", "utf-8") as f: 
    .....:  f.write(obj_xml) 
    .....: 

錯誤我打無法將「字節」對象爲str隱含

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-459-61a3d9d572a6> in <module>() 
     1 with codecs.open(xmlOutFile, "+ab", "utf-8") as f: 
----> 2  f.write(obj_xml) 
     3 

C:\Python3\lib\codecs.py in write(self, data) 
    698  def write(self, data): 
    699 
--> 700   return self.writer.write(data) 
    701 
    702  def writelines(self, list): 

C:\Python3\lib\codecs.py in write(self, object) 
    354   """ Writes the object's contents encoded to self.stream. 
    355   """ 
--> 356   data, consumed = self.encode(object, self.errors) 
    357   self.stream.write(data) 
    358 

類型錯誤:無法將「字節」對象隱含str的 我如何去寫內容obj_xml的文件?

+0

那麼不要這樣做。 –

回答

0

codecs.open需要一個Unicode字符串,並在寫入時將其編碼爲字節。您已經有了一個字節對象,所以只需以二進制模式打開文件並寫入對象:

with open(xmlOutFile,'+ab') as f: 
    f.write(obj_xml) 
相關問題