python3文件写入失败_在python3中写入csv中的io.BytesIO失败

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)

Gives this error on Python3:

> writer.writerow(line)

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

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

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

解决方案

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.

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

In Python3 the code above prints

b'foo,bar\r\n'

In Python2 the code above prints

'foo,bar\r\n'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值