Skip to main content
 首页 » 编程设计

python之用 Python 写一个 csv 文件 : error with function writerows

2025年05月04日27mate10pro

尝试将列表的列表保存到 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) 

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

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' 

有人知道缺少什么吗?

请您参考如下方法:

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

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

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

参见 csv module footnote :

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 选项可以更好地处理这个问题。