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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29840849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:05:46  来源:igfitidea点击:

Writing a .CSV file in Python that works for both Python 2.7+ and Python 3.3+ in Windows

pythonpython-2.7csvpython-3.xpython-3.3

提问by Tamerz

EDIT: I put it in the title, but just realized I didn't mention it in the body. This seems to be specific to Windows.

编辑:我把它放在标题中,但刚刚意识到我没有在正文中提到它。这似乎是特定于 Windows 的。

I'm having a hard time writing output using the csvPython module in a script that works with both Python 2.7 and 3.3.

我很难csv在一个脚本中使用Python 模块编写输出,该脚本适用于 Python 2.7 和 3.3。

First try which works as expected in Python 2.7:

首先尝试在 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)

However, when that same thing is run in Python 3.3 you wind up with:

然而,当同样的事情在 Python 3.3 中运行时,你会得到:

TypeError: 'str' does not support the buffer interface

So I change 'wb'to 'wt'and it runs, but now I have an extra blank row every other line in the file.

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

To fix that, I change:

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

with open('test.csv', 'wt') as csv_file:

to:

到:

with open('test.csv', 'wt', newline='') as csv_file:

But now, it breaks Python 2.7:

但是现在,它打破了 Python 2.7:

TypeError: 'newline' is an invalid keyword argument for this function

I know I could just do something like:

我知道我可以这样做:

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)

However, that has some seriously bad duplication.

然而,这有一些严重的重复。

Does anyone have a cleaner way of doing this?

有没有人有更干净的方法来做到这一点?

EDIT: The test data is simple and has no newlines or anything:

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

items = [{'header1': 'value', 'header2': 'value2'},
         {'header1': 'blah1', 'header2': 'blah2'}]

采纳答案by skyline75489

I've tried a few ways. As far as I can see, simple using 'w'could be a solution:

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

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

回答by cdarke

Here's a simpler generic way:

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

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)

The principle here is not to try to fight the differences between Python 2 and 3 but to have conditional code. You can only go so far in writing code without this kind of test, sooner or later you will have to test the Python version.

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