2011-04-01 151 views
91

我已將Python 2.7的腳本轉換爲3.2,並且有一些錯誤。builtins.TypeError:必須是str,而不是字節

# -*- coding: utf-8 -*- 
import time 
from datetime import date 
from lxml import etree 
from collections import OrderedDict 

# Create the root element 
page = etree.Element('results') 

# Make a new document tree 
doc = etree.ElementTree(page) 

# Add the subelements 
pageElement = etree.SubElement(page, 'Country',Tim = 'Now', 
             name='Germany', AnotherParameter = 'Bye', 
             Code='DE', 
             Storage='Basic') 
pageElement = etree.SubElement(page, 'City', 
             name='Germany', 
             Code='PZ', 
             Storage='Basic',AnotherParameter = 'Hello') 
# For multiple multiple attributes, use as shown above 

# Save to XML file 
outFile = open('output.xml', 'w') 
doc.write(outFile) 

在最後一行我得到了一個錯誤:

builtins.TypeError: must be str, not bytes 
File "C:\PythonExamples\XmlReportGeneratorExample.py", line 29, in <module> 
    doc.write(outFile) 
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 1853, in lxml.etree._ElementTree.write (src/lxml/lxml.etree.c:44355) 
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 478, in lxml.etree._tofilelike (src/lxml/lxml.etree.c:90649) 
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 282, in lxml.etree._ExceptionContext._raise_if_stored (src/lxml/lxml.etree.c:7972) 
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 378, in lxml.etree._FilelikeWriter.write (src/lxml/lxml.etree.c:89527) 

我已經安裝了蟒蛇3.2,我已經安裝了LXML-2.3.win32-py3.2.exe。

在2.7它工作。

+10

沒有真正調查過這一點,但一個簡單的猜測是你應該以二進制模式打開文件。 – 2011-04-01 11:39:03

回答

199

outfile應該是二進制模式。

outFile = open('output.xml', 'wb') 
+49

頭腦風暴。 Python3已經重新設想了如何處理這個小小的'b'。它過去只會讓那些忘記包含它的Windows用戶煩惱(或者因爲他們使用的是stdio而不能這樣做)。現在它可以在所有平臺上激怒Python用戶。希望這將是值得的痛苦。 – nobar 2013-08-17 06:11:04

+5

如果你正在解析文本,這絕對是值得的。 – 2014-01-15 21:56:50

+0

@nobar需要例如關閉通用換行支持,http://legacy.python.org/dev/peps/pep-0278/,默認在Python 3中啓用 – user7610 2014-07-26 15:28:27

1

將二進制文件轉換爲base64 &反之亦然。在python 3.5.2中證明

import base64 

read_file = open('/tmp/newgalax.png', 'rb') 
data = read_file.read() 

b64 = base64.b64encode(data) 

print (b64) 

# Save file 
decode_b64 = base64.b64decode(b64) 
out_file = open('/tmp/out_newgalax.png', 'wb') 
out_file.write(decode_b64) 

# Test in python 3.5.2 
+0

更多當然不能:) – djperalta 2017-04-23 01:06:16

+1

請包括一個解釋,一個代碼只有轉儲並不能真正幫助人們理解解決方案。 – 2017-04-23 10:51:10

相關問題