8

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'

Felipe Augusto
  • 7,733
  • 10
  • 39
  • 73
Chenxi
  • 297
  • 1
  • 4
  • 15

2 Answers2

14

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?

Deejpake
  • 424
  • 4
  • 11
  • Thanks! I changed 3rd row of first part to: `writer.writerow(out_data.keys().encode('utf-8'))` But the following error message shows: **'odict_keys' object has no attribute 'encode'** – Chenxi Aug 21 '18 at 02:45
11

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:
Felipe Augusto
  • 7,733
  • 10
  • 39
  • 73
Chenxi
  • 297
  • 1
  • 4
  • 15