在python3中写入csv中的io.BytesIO失败 [英] Writing to io.BytesIO in csv fails in python3

查看:497
本文介绍了在python3中写入csv中的io.BytesIO失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写python 2/3兼容代码以将字符串写入csv文件对象.这段代码:

I am trying to write python 2/3 compatible code to write strings to csv file object. This code:

line_as_list = [line.encode() for line in line_as_list]
writer_file =  io.BytesIO()
writer = csv.writer(writer_file, dialect=dialect, delimiter=self.delimiter)
for line in line_as_list:
    assert isinstance(line,bytes)
    writer.writerow(line)

在Python3上给出此错误:

Gives this error on Python3:

>           writer.writerow(line)
E           TypeError: a bytes-like object is required, not 'str'

但是assert的类型没有问题,那么为什么csv会创建错误?

But assert has no problem with the type, so why is csv creating an error?

我不能仅对Python 2和3使用BytesIO吗?问题出在哪里?

Can't I use BytesIO only for both Python 2 and 3? Where is the problem here?

推荐答案

在Python3中,csv.writer期望在文本模式下打开类似文件的对象. 在Python2中,csv.writer需要以二进制模式打开的类似文件的对象.

In Python3 csv.writer expects a file-like object opened in text mode. In Python2, csv.writer expects a file-like object opened in binary mode.

因此,在Python3中使用io.StringIO,而在Python2中使用io.BytesIO:

Therefore, in Python3, use io.StringIO, while in Python2 use io.BytesIO:

import io
import csv
import sys
PY3 = sys.version_info[0] == 3

line_as_list = [u'foo', u'bar']
encoding = 'utf-8'

if PY3:
    writer_file =  io.StringIO()
else:
    writer_file =  io.BytesIO()
    line_as_list = [line.encode(encoding) for line in line_as_list]

writer = csv.writer(writer_file, dialect='excel', delimiter=',')
writer.writerow(line_as_list)
content = writer_file.getvalue()

if PY3:
    content = content.encode(encoding)

print(type(content))
print(repr(content))


在Python3中,上面的代码会打印


In Python3 the code above prints

<class 'bytes'>
b'foo,bar\r\n'

在Python2中,上面的代码会打印

In Python2 the code above prints

<type 'str'>
'foo,bar\r\n'

这篇关于在python3中写入csv中的io.BytesIO失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆