Python 2 CSV writer在Windows上生成错误的行终止符 [英] Python 2 CSV writer produces wrong line terminator on Windows

查看:146
本文介绍了Python 2 CSV writer在Windows上生成错误的行终止符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据其文档 csv.writer应该默认使用'\r\\\
'作为lineterminator。

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")

打印

\r\n
\r\n

。但是,创建的csv文件使用lineterminator'\r\r\\\
'

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

这是一个错误, csv.writer?

Is this a bug or is there something wrong in my usage of csv.writer?

Python版本:


ActivePython 2.6.2.2
Software Inc.)基于Python 2.6.2
(r262:71600,2009年4月21日,15:05:37)
[MSC v.1500 32位(Intel)]在win32

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

推荐答案

在Python 2.x中,始终以二进制模式打开文件,如记录所示。 csv 按照您的预期写入 \r\\\
,但是基本的Windows文本文件机制 \\\
\r\\\
...总效果: \\ r \r\\\

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

csv.writer 文档:


如果 csvfile 是一个文件对象,它必须用平台上的'b'差异。

If csvfile is a file object, it must be opened with the 'b' flag on platforms where that makes a difference.

似乎对于真正说出主要罪犯的名字有些沉默: - )

There seems to be some reticence about actually uttering the name of the main culprit :-)

这篇关于Python 2 CSV writer在Windows上生成错误的行终止符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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