在Python中编写.CSV文件,适用于Windows中的Python 2.7+和Python 3.3+

Tam*_*erz 15 python csv python-2.7 python-3.x python-3.3

编辑:我把它放在标题中,但只是意识到我没有在体内提到它.这似乎是Windows特有的.

我很难csv在一个兼容Python 2.7和3.3的脚本中使用Python模块编写输出.

第一次尝试在Python 2.7中按预期工作:

with open('test.csv', 'wb') as csv_file:
    writer = csv.DictWriter(csv_file, ['header1', 'header2'])
    writer.writeheader()
    for item in items:
        writer.writerow(item)
Run Code Online (Sandbox Code Playgroud)

但是,当在Python 3.3中运行同样的事情时,你最终得到:

TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)

所以我改变'wb''wt'它运行,但现在我有一个额外的空白行中的文件每隔一行.

为了解决这个问题,我改变了:

with open('test.csv', 'wt') as csv_file:
Run Code Online (Sandbox Code Playgroud)

至:

with open('test.csv', 'wt', newline='') as csv_file:
Run Code Online (Sandbox Code Playgroud)

但现在,它打破了Python 2.7:

TypeError: 'newline' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

try:
    with open('test.csv', 'wt', newline='') as csv_file:
        writer = csv.DictWriter(csv_file, ['header1', 'header2'])
        writer.writeheader()
        for item in items:
            writer.writerow(item)
except TypeError:
    with open('test.csv', 'wb') as csv_file:
        writer = csv.DictWriter(csv_file, ['header1', 'header2'])
        writer.writeheader()
        for item in items:
            writer.writerow(item)
Run Code Online (Sandbox Code Playgroud)

但是,这有一些严重不好的重复.

有没有人有更清洁的方式这样做?

编辑:测试数据很简单,没有新行或任何东西:

items = [{'header1': 'value', 'header2': 'value2'},
         {'header1': 'blah1', 'header2': 'blah2'}]
Run Code Online (Sandbox Code Playgroud)

cda*_*rke 8

这是一种更简单的通用方法:

import sys

if sys.version_info[0] == 2:  # Not named on 2.6
    access = 'wb'
    kwargs = {}
else:
    access = 'wt'
    kwargs = {'newline':''}

with open('test.csv', access, **kwargs) as csv_file:
    writer = csv.DictWriter(csv_file, ['header1', 'header2'])
    writer.writeheader()
    for item in items:
        writer.writerow(item)
Run Code Online (Sandbox Code Playgroud)

这里的原则不是试图对抗Python 2和3之间的差异,而是要有条件代码.你只能在没有这种测试的情况下编写代码,迟早你将不得不测试Python版本.


sky*_*489 7

我尝试了几种方法.据我所知,简单使用'w'可能是一个解决方案:

with open('test.csv', 'w') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=['header1', 'header2'], lineterminator='\n')
    # write something
Run Code Online (Sandbox Code Playgroud)