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

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

问题描述

根据 其文档 csv.writer 应该使用' ' 默认为换行符.

According to the its documentation csv.writer should use ' ' 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").replace("
", "\n")
    writer.writerows(rows)
    print writer.dialect.lineterminator.replace("
", "\r").replace("
", "\n")

这个打印





正如预期的那样.但是,创建的 csv 文件使用换行符 ' '

as expected. But, the created csv-file uses the lineterminator ' '

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 (ActiveStateSoftware 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

在 Windows Vista 上

on Windows Vista

推荐答案

在 Python 2.x 中,始终按照文档中的说明以 二进制 模式打开文件.csv 按照您的预期写入 ,但随后底层的 Windows 文本文件机制介入并将 更改为 ... 总效果:

In Python 2.x, always open your file in binary mode, as documented. csv writes as you expected, but then the underlying Windows text file mechanism cuts in and changes that to ... total effect:

来自 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 :-)

正如@jebob 在对此答案的评论中所提到的,并基于@Dave Burton 的 answer,处理在 Python 2 和 3 中的这种情况下,您应该执行以下操作:

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:

if sys.version_info >= (3,0,0):
    f = open(filename, 'w', newline='')
else:
    f = open(filename, 'wb')

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

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