2

I declare a BytesIO() object to write through csv.writer as:

lines = ["abc", "def", "ghi"]
writer_file =  io.BytesIO()
writer = csv.writer(writer_file)        
writer.writerow(str(lines).encode("utf-8"))

but I get an error:

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

but when I check the types, I get a bytes object.

In [14]: type(str(lines).encode("utf-8"))
Out[14]: bytes

What does this mean?

Note: I can't use io.StringIO() to keep this code compatible for python2. (Basing my assumptions on this: different io types for csv in python 2 and 3 )

Community
  • 1
  • 1
goelakash
  • 2,502
  • 4
  • 40
  • 56
  • You can use `io.StringIO` and still be compatible with python2... You would be using unicode strings on python3, but no reason why this would make a difference in the outcome.. Both python versions would be using their `str` class. Another option is to just use always Unicode... It is better anyway – JBernardo Jun 16 '16 at 19:17
  • @JBernardo http://stackoverflow.com/questions/13120127/how-can-i-use-io-stringio-with-the-csv-module – goelakash Jun 16 '16 at 19:34

1 Answers1

2

For the time being, I just check the python system version and apply the appropriate io.*IO() object for csv writing as:

import sys

lines = ["abc", "def", "ghi"]
if sys.version_info >= (3.0):
    writer_file =  io.StringIO()
else:
    writer_file =  io.BytesIO()

writer = csv.writer(writer_file)        
writer.writerow(lines)
goelakash
  • 2,502
  • 4
  • 40
  • 56