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

Che*_*nxi 2 string types python-3.x

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

只写一次标题

if header_written == False:
    header = out_data.keys()
    writer.writerow(out_data.keys()) # write headers
    header_written = True
Run Code Online (Sandbox Code Playgroud)

写值

writer.writerow(out_data.values()) #write rows
del out_data  #del object
del row_data #del dict object
Run Code Online (Sandbox Code Playgroud)

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

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

Dee*_*ake 11

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

bytes = string.encode(encoding='UTF-8')
Run Code Online (Sandbox Code Playgroud)

更多信息在这里

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


Che*_*nxi 5

这是关于开始的部分。

更改

with open('r2.csv', 'r') as infile , open("output2.csv",'wb') as resultFile:
Run Code Online (Sandbox Code Playgroud)

至

with open('r2.csv', 'r') as infile , open("output2.csv",'w') as resultFile:
Run Code Online (Sandbox Code Playgroud)