Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
write()参数必须是str,而不是python字节_Python_Api - Fatal编程技术网

write()参数必须是str,而不是python字节

write()参数必须是str,而不是python字节,python,api,Python,Api,我是python新手。我得到了这个预先编写的代码,可以将数据下载到报告中。但是我得到了错误 “write()参数必须是str,而不是bytes” 请参阅下面的代码 def _download_report(service, response, ostream): logger.info('Downloading keyword report') written_header = False for fragment in range(len(response.files

我是python新手。我得到了这个预先编写的代码,可以将数据下载到报告中。但是我得到了错误

“write()参数必须是str,而不是bytes”

请参阅下面的代码

def _download_report(service, response, ostream):

    logger.info('Downloading keyword report')
    written_header = False
    for fragment in range(len(response.files)):
      file_request = service.reports().getFile(
        reportId=response.id_, reportFragment=fragment)
      istream = io.BytesIO(file_request.execute())

    if written_header:
      istream.readline()
    else:
      written_header = True
    ostream.write(istream.read())

您需要将最后一行更改为

ostream.write(istream.read().decode('utf-8'))
ostream.write(istream.read().decode('utf-8'))

注:您可能需要用数据中的任何编码替换“utf-8”,以详细说明@sgDysregulation的答案:

python 3的一个特点是字符串(
'hello,world'
)和二进制字符串(
b'hello,world'
)基本上是不兼容的。例如,如果您熟悉基本文件I/O,有两种模式可以读取文件-可以使用
open('file.txt','r')
,在读取文件时返回unicode字符串,或者使用
open('file,txt','rb')
,返回二进制字符串。这同样适用于写入-您不能在模式
'wb'
下正确写入字符串,也不能在模式
'w'
下写入二进制字符串

在这种情况下,
istream
从读取时返回二进制字符串,而
ostream
则希望写入unicode字符串。解决方案是将编码从一种更改为另一种,并按照sgDysregulation的建议执行:

ostream.write(istream.read().decode('utf-8'))

这假设二进制字符串是以utf-8格式编码的,可能是这样。否则,您可能必须使用不同的格式。

您必须对BytesIO对象进行解码,以获得可写入文件的字符串: