无法在Python3中使用csv.writer编写类似字节的字符串

时间:2016-06-16 18:33:32

标签: string python-3.x csv

我声明一个BytesIO()对象通过csv.writer写为:

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

但是我收到了错误:

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

但是当我检查类型时,我得到一个bytes对象。

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

这是什么意思?

注意:我无法使用io.StringIO()来保持此代码与python2兼容。 (根据我的假设:different io types for csv in python 2 and 3

1 个答案:

答案 0 :(得分:1)

暂时,我只检查python系统版本并将适当的io.*IO()对象应用于csv写作:

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)