string - Python 3.5 需要写一个类似字节的对象,而不是“str" [英] string - Python 3.5 write a bytes-like object is required, not 'str'

查看:33
本文介绍了string - Python 3.5 需要写一个类似字节的对象,而不是“str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的 Python 代码适用于 Python 2,

My following python code works for Python 2,

if header_written == False:
    header = out_data.keys()
    writer.writerow(out_data.keys()) # write headers
    header_written = True

写入值

writer.writerow(out_data.values()) #write rows
del out_data  #del object
del row_data #del dict object

但在 Python 3 中,它返回以下错误:

but in Python 3, it returns the following error:

TypeError: 需要一个类似字节的对象,而不是 'str'

TypeError: a bytes-like object is required, not 'str'

推荐答案

您必须将其转换为字节.你可以这样做.

You have to convert it to bytes. You can do it like this.

bytes = string.encode(encoding='UTF-8')

更多信息在这里

在 Python 中将字符串转换为字节的最佳方法3?

这篇关于string - Python 3.5 需要写一个类似字节的对象,而不是“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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