Python 2 CSV 编写器在 Windows 上产生错误的行终止符
根据 其文档 csv.writer 应该使用 '\r默认情况下,\n' 作为行终止符。
import csv
with open("test.csv", "w") as f:
writer = csv.writer(f)
rows = [(0,1,2,3,4),
(-0,-1,-2,-3,-4),
("a","b","c","d","e"),
("A","B","C","D","E")]
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
writer.writerows(rows)
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
这
\r\n
\r\n
将按预期打印。 但是,创建的 csv 文件使用行终止符 '\r\r\n'
0,1,2,3,4
0,-1,-2,-3,-4
a,b,c,d,e
A,B,C,D,E
这是一个错误还是我对 csv.writer 的使用有问题?
Python版本:
ActivePython 2.6.2.2(ActiveState Software Inc.)基于Python 2.6.2 (r262:71600,2009 年 4 月 21 日,15:05:37) [MSC v.1500 32 位(英特尔)] 在 win32 上
在 Windows Vista 上的win32 上
According to the its documentation csv.writer should use '\r\n' as lineterminator by default.
import csv
with open("test.csv", "w") as f:
writer = csv.writer(f)
rows = [(0,1,2,3,4),
(-0,-1,-2,-3,-4),
("a","b","c","d","e"),
("A","B","C","D","E")]
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
writer.writerows(rows)
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
This prints
\r\n
\r\n
as expected. But, the created csv-file uses the lineterminator '\r\r\n'
0,1,2,3,4
0,-1,-2,-3,-4
a,b,c,d,e
A,B,C,D,E
Is this a bug or is there something wrong in my usage of csv.writer?
Python version:
ActivePython 2.6.2.2 (ActiveState
Software Inc.) based on Python 2.6.2
(r262:71600, Apr 21 2009, 15:05:37)
[MSC v.1500 32 bit (Intel)] on win32
on Windows Vista
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Python 2.x 中,始终以二进制模式打开文件,如文档所述。
csv
按照您的预期写入\r\n
,但随后底层 Windows 文本文件机制介入并将\n
更改为\r\n
...总效果:\r\r\n
来自
csv.writer
文档:对于实际说出主要罪魁祸首的名字似乎有些沉默:-)
编辑:正如 @jebob 在这个答案的评论中提到的,基于 @Dave Burton 的 答案,要在Python 2和3中处理这种情况,您应该执行以下操作:
In Python 2.x, always open your file in binary mode, as documented.
csv
writes\r\n
as you expected, but then the underlying Windows text file mechanism cuts in and changes that\n
to\r\n
... total effect:\r\r\n
From the
csv.writer
documentation:There seems to be some reticence about actually uttering the name of the main culprit :-)
Edit: As mentioned by @jebob in the comments to this answer and based on @Dave Burton's answer, to handle this case in both Python 2 and 3, you should do the following:
不幸的是,它与 Python 3 的 csv 模块有点不同,但此代码适用于 Python 2 和 Python 3:
Unfortunately, it's a bit different with the csv module for Python 3, but this code will work on both Python 2 and Python 3:
要更改 Python 2.7 csv writer 中的行终止符,请使用
writer = csv.writer(f, delimiter = '|', lineterminator='\n')
这是更改默认分隔符的更简单方法来自\r\n。
To change the line terminator in Python 2.7 csv writer use
writer = csv.writer(f, delimiter = '|', lineterminator='\n')
This is a much simpler way to change the default delimiter from \r\n.