用Python编写一个csv文件:函数writerows错误 [英] Write a csv file in Python : error with function writerows

查看:357
本文介绍了用Python编写一个csv文件:函数writerows错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 <module>
writer.writerows(a)
TypeError: a bytes-like object is required, not 'str'

任何人都知道缺少什么吗?

Anyone knows what is missing?

推荐答案

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

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

通过拖放b以文本模式打开文件.还建议您设置newline='':

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:

请参见 csv模块脚注:

See the csv module footnote:

如果未指定newline='',则不会正确解释加引号的字段中嵌入的换行符,并且在使用\r\n lindings的平台上将添加额外的\r.指定newline=''应该总是安全的,因为csv模块会执行自己的(通用)换行符处理.

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.

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

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.

这篇关于用Python编写一个csv文件:函数writerows错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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