用Python写一个csv文件:函数writerow出错

Ant*_*ser 1 python csv python-3.x

试图将列表列表保存到csv文件中,我使用了csv模块.这是我的脚本:

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)
Run Code Online (Sandbox Code Playgroud)

当我运行此脚本时,会出现一条错误消息:

Traceback (most recent call last):
File "csv-ex.py", line 5, in <module>
writer.writerows(a)
TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

谁知道缺少什么?

Mar*_*ers 5

您以二进制模式打开文件,但csv.writer()对象发送字符串.

删除后,以文本模式打开文件b.还建议您设置newline='':

with open("output.csv", "w", newline='') as f:
Run Code Online (Sandbox Code Playgroud)

csv模块脚注:

如果newline=''未指定,则引用字段中嵌入的换行符将无法正确解释,并且\r\n在写入时使用换行符的平台\r上将添加额外的行.newline=''由于csv模块执行自己的(通用)换行处理,因此指定它应始终是安全的.

在Python 2中,出于同样的原因,建议以二进制模式打开文件,但Python 3中的I/O层使用该newline选项可以更好地处理这个问题.