python的csv模块的write_rows_用Python编写一个CSV文件:函数writerows错误

Trying to save a list of lists into a csv file, I used the csv module. Here is my script :

import csv

a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

with open("output.csv", "wb") as f:

writer = csv.writer(f)

writer.writerows(a)

When I run this script, an error message appears :

Traceback (most recent call last):

File "csv-ex.py", line 5, in

writer.writerows(a)

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

Anyone knows what is missing?

解决方案

You opened the file in binary mode, but the csv.writer() object sends strings.

Open the file in text mode by dropping the b. It is also recommended you set newline='':

with open("output.csv", "w", newline='') as f:

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

In Python 2, it was recommended to open the file in binary mode for the same reasons, but the I/O layer in Python 3 handles this much better with the newline option.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值