Python3错误:initial_value必须是str或None,与StringIO一起使用。
Python3错误:initial_value必须是str或None,与StringIO一起使用。
在将代码从python2
迁移到3
时,当从URL读取内容时,出现以下错误:
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,它可以正常工作。