用Python编写一个csv文件:函数writerows错误 [英] Write a csv file in Python : error with function 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 specifynewline=''
, since thecsv
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屋!