简体   繁体   中英

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

My following python code works for 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:

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')

More info here

Best way to convert string to bytes in 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM