python - 如何在没有空行的python中在csv文件中写入元组

标签 python csv

我正在尝试将几个元组写入一个 csv 文件。

这是我尝试过的:

import csv
out_file = open('csv_write.csv', 'w')
writer = csv.writer(out_file)
writer.writerow((0, 1, 2))
writer.writerow((3, 4, 5))
out_file.close()

这有效,但没有达到预期效果。注意电子表格中的空白行:

screenshot of spreadsheet rows showing unwanted blank lines

在文本编辑器中,文件如下所示:

0,1,2
<blank line>
3,4,5
<blank line>

(共 4 行)

没有这些空白行我怎么写?

最佳答案

csv 模块有自己的行尾处理,并要求以特定方式打开输出文件:

out_file = open('csv_write.csv', 'wb')             # Python 2.x
out_file = open('csv_write.csv', 'w', newline='')  # Python 3.x

引用 http://docs.python.org/2.7/library/csv.html?highlight=csv#csv.writer :

...it must be opened with the ‘b’ flag on platforms where that makes a difference.

http://docs.python.org/3.3/library/csv.html?highlight=csv#csv.writer :

...it should be opened with newline=''...

您的空白行是由于 csv 模块的默认“方言”是 excel。该方言定义 lineterminator='\r\n' 并且这些字符直接写入流。在 Python 2 上以文本模式打开输出文件或在 Python 3 上不使用 newline='' “在不同的平台上”(Windows) 将所有 \n 翻译成输出流到 \r\n,结果是 \r\r\n。这会导致额外的空白行。

关于python - 如何在没有空行的python中在csv文件中写入元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18328133/

相关文章:

jQuery dataTables CSV 服务器数据

python - Matplotlib/Genfromtxt : Multiple plots against time, 跳过 .csv 中缺失的数据点

python记录到数据库

python - 使用 Go/Python 使用 CSRF token 登录站点

python - Django 客户端证书提示

c# - 传入 CSV Excel 工作表的选项卡名称

mysql - 如何上传文件(csv 或文本)并在 Zope 框架中读取内容

python - 在 Python 3.4 中打印列表的总和

python - 使用 .split 隔离 Python 中未定义的关键字

perl - CSV 和带空格的字段