builtins.TypeError:必须为str,而不是字节


219

我已经将脚本从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上可以使用。


10
并没有对此进行真正的调查,但是快速猜测是您应该以二进制模式打开文件。
Sven Marnach 2011年

Answers:


482

输出文件应处于二进制模式。

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

100
精神震撼。Python3重新构想了处理那个小“ b”的方法。它曾经只惹恼那些会忘记包括它的Windows用户(或者因为使用stdio而不会)。现在,它可以使所有平台上的Python用户烦恼。希望这是值得的。
nobar 2013年

5
如果您要解析文本,那绝对值得。
Lennart Regebro 2014年

@nobar需要关闭通用换行支持,legacy.python.org / dev / peps / pep-0278,这在Python 3中是默认启用的
user7610 2014年

同样适用于python3的gzip!json.load(gzip.open('file.json.gz'))失败,json.load(gzip.open('file.json.gz', 'rt'))成功!
滚刀

@LennartRegebro,如果系统设置意外,则不是。二进制是最好的,并且不易出错。如果可行,则确实可行。至于文本,总是涉及“如果”。
Pacerier '17

6

将二进制文件转换为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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.