Python3错误:使用StringIO时,initial_value必须为str或None [英] Python3 error: initial_value must be str or None, with StringIO

查看:1442
本文介绍了Python3错误:使用StringIO时,initial_value必须为str或None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将代码从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位

StringIOcStringIO模块不见了.而是导入io模块,并分别对文本和数据使用io.StringIOio.BytesIO.

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

这篇关于Python3错误:使用StringIO时,initial_value必须为str或None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆