内置类型错误:必须为str,而不是bytes
我把我的脚本从Python 2.7转换到了3.2版本,但现在遇到了一个错误。
# -*- 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)
我已经安装了Python 3.2,也安装了lxml-2.3.win32-py3.2.exe。
在Python 2.7上,这个脚本是可以正常运行的。
3 个回答
0
如果因为某种原因,输出文件是用 mode='w'
打开的,而不能用 'wb'
重新打开,那么可以采用一个变通的方法。你可以通过访问 TextIOWrapper
的 .buffer
属性来创建一个 BufferedWriter
(这个对象在用 mode='wb'
打开文件时会自动生成),然后就可以进行写入操作了。
s = """
<country name="Liechtenstein">
<year>2008</year>
<gdppc>141100</gdppc>
</country>
"""
import xml.etree.ElementTree as ET
doc = ET.ElementTree(ET.fromstring(s))
outFile = open('output.xml', 'w')
doc.write(outFile.buffer) # <--- buffer here
outFile.close()
9
将二进制文件转换为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
649
输出文件应该以二进制模式打开。
outFile = open('output.xml', 'wb')