简体   繁体   English

字符串 - Python 3.5 需要写一个类似字节的对象,而不是“str”

[英]string - Python 3.5 write a bytes-like object is required, not 'str'

My following python code works for Python 2,我的以下 Python 代码适用于 Python 2,

Write header only once只写一次标题

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

Write values写入值

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

but in Python 3, it returns the following error:但在 Python 3 中,它返回以下错误:

TypeError: a bytes-like object is required, not 'str'类型错误:需要类似字节的对象,而不是“str”

You have to convert it to bytes.您必须将其转换为字节。 You can do it like this.你可以这样做。

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

More info here更多信息在这里

Best way to convert string to bytes in Python 3? 在 Python 3 中将字符串转换为字节的最佳方法?

It is about the initial part.这是关于初始部分。

Change改变

with open('r2.csv', 'r') as infile , open("output2.csv",'wb') as resultFile:

To

with open('r2.csv', 'r') as infile , open("output2.csv",'w') as resultFile:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:将字符串写入文件需要类似字节的 object,而不是“str” - TypeError: a bytes-like object is required, not 'str', for writing string to file Python错误:TypeError:需要一个类似字节的对象,而不是&#39;str&#39; - Python error: TypeError: a bytes-like object is required, not 'str' “需要类似字节的 object,而不是 str” Python 中的错误 - “A bytes-like object is required, not str” Error in Python 需要类似字节的 object,而不是“str” JSON 文件作为 STR 打开 - a bytes-like object is required, not 'str' JSON File opened as STR Python3 - 在类型的对象上“需要一个类似字节的对象,而不是&#39;str&#39;”<class 'bytes'> - Python3 - "a bytes-like object is required, not 'str'" on object of type <class 'bytes'> TypeError:需要类似字节的 object,不是“str”,但类型显示字节 - TypeError: a bytes-like object is required, not 'str' but type shows bytes 将 Python2 更改为 Python3 错误:TypeError:需要类似字节的对象,而不是“str” - Changing Python2 to Python3 Error: TypeError: a bytes-like object is required, not 'str' 子进程“类型错误:需要一个类似字节的对象,而不是‘str’” - subprocess "TypeError: a bytes-like object is required, not 'str'" 类型错误:需要类似字节的 object,而不是鼠标模拟的“str” - TypeError: a bytes-like object is required, not 'str' with a mouse emulation 无法拆分,需要一个类似字节的对象,而不是“str” - Cannot split, a bytes-like object is required, not 'str'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM