Python3错误:使用StringIO时,initial_value必须为str或None [英] Python3 error: initial_value must be str or None, with StringIO
问题描述
将代码从python2
移植到3
时,从URL读取时出现此错误
While porting code from python2
to 3
, I get this error when reading from a URL
TypeError:initial_value必须为str或None,而不是字节.
TypeError: initial_value must be str or None, not bytes.
import urllib
import json
import gzip
from urllib.parse import urlencode
from urllib.request import Request
service_url = 'https://babelfy.io/v1/disambiguate'
text = 'BabelNet is both a multilingual encyclopedic dictionary and a semantic network'
lang = 'EN'
Key = 'KEY'
params = {
'text' : text,
'key' : Key,
'lang' :'EN'
}
url = service_url + '?' + urllib.urlencode(params)
request = Request(url)
request.add_header('Accept-encoding', 'gzip')
response = urllib.request.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO(response.read())
f = gzip.GzipFile(fileobj=buf)
data = json.loads(f.read())
此行抛出异常
buf = StringIO(response.read())
如果我使用python2,它可以正常工作.
If I use python2, it works fine.
推荐答案
response.read()
返回bytes
的实例,而 BytesIO
.
response.read()
returns an instance of bytes
while StringIO
is an in-memory stream for text only. Use BytesIO
instead.
来自 Python 3.0的新功能-文字对比.数据而不是UnicodeVs. 8位
StringIO
和cStringIO
模块不见了.而是导入io
模块,并分别对文本和数据使用io.StringIO
或io.BytesIO
.
The
StringIO
andcStringIO
modules are gone. Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.
这篇关于Python3错误:使用StringIO时,initial_value必须为str或None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!