在python 2或python 3中编写csv文件的便携方式 [英] portable way to write csv file in python 2 or python 3

查看:27
本文介绍了在python 2或python 3中编写csv文件的便携方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Windows 机器上,我通常在 python 2 中这样做来编写一个 csv 文件:

On my Windows box, I usually did this in python 2 to write a csv file:

import csv
f = open("out.csv","wb")
cr = csv.writer(f,delimiter=';')
cr.writerow(["a","b","c"])
f.close()

既然 python 3 禁止将文本文件写为二进制文件,那段代码就不再起作用了.这有效:

Now that python 3 forbids writing text files as binary, that piece of code does not work anymore. That works:

import csv
f = open("out.csv","w",newline='')
cr = csv.writer(f,delimiter=';')
cr.writerow(["a","b","c"])
f.close()

问题是:newline 参数对于 Python 2 来说是未知的.

Problem is: newline parameter is unknown to Python 2.

当然,省略换行符会导致 csv 文件的 字符过多,因此不可接受.

Of course, omitting the newline results in a csv file with too many chars, so not acceptable.

我目前正在执行一个向后兼容的过程,以逐步从 python 2 迁移到 python 3.5我的所有模块中都有很多这样的语句.

I'm currently performing a backwards compatible process to progressively migrate from python 2 to python 3.5 There are a lot of those statements in all my modules.

我的解决方案是将代码嵌入到自定义模块中,自定义模块返回文件处理程序 + 编写器对象.python 版本检查在模块内部完成,这允许使用我的模块的任何模块在没有太多黑客攻击的情况下工作任何 python 版本.

My solution was embedding the code in a custom module, and the custom module returns file handler + writer object. A python version check is done inside the module, which allows any module using my module to work whatever python version without too much hacking.

有更好的方法吗?

推荐答案

在 Windows 上,我发现了一个 python 2 &3 种合规方式更改 csv lineterminator 选项(默认为 " " 这使得一个 太多时文件在 Windows 中以文本模式打开)

On Windows, I found a python 2 & 3 compliant way of doing it changing csv lineterminator option (which defaults to " " which makes one too many when file is open in text mode in Windows)

import csv

with open("out.csv","w") as f:
    cr = csv.writer(f,delimiter=";",lineterminator="
")
    cr.writerow(["a","b","c"])
    cr.writerow(["d","e","f"])
    cr.writerow(["a","b","c"])
    cr.writerow(["d","e","f"])

无论 python 版本如何,都会创建一个没有臭名昭著的空白行"的 csv 文件.

Whatever the python version, that will create a csv file without the infamous "blank lines".

唯一的缺点是在 Linux 上,这种方法会产生 -free 文件,这可能不是标准的(尽管文件在 excel 中仍然可以正常打开,没有空行,仍然有几行:))

The only drawback is that on Linux, this method would produce -free files, which is maybe not the standard (although files still opens properly in excel, no blank lines and still several lines :))

问题在 3.6.2 上仍然存在(就像我前段时间应该检查过的那样)

the problem persists on 3.6.2 (Just checked myself like I should have some time ago)

另一种方法是使用字典作为参数:

An alternative is to use a dictionary as arguments:

write_args = {"mode":"wb"} if bytes is str else {"mode":"w","newline":""}

(比较bytesstr是区分python 2和python 3的众多方法之一,在python 3中类型是不同的,这与我们当前的顺便说一句.

(comparing bytes to str is one of the many ways to tell python 2 from python 3, in python 3 types are different, and it's very related to our current problem BTW).

现在我们可以通过 args 解包传递这些参数:

Now we can pass those arguments with args unpacking:

with open("out.csv",**write_args) as f:
    cr = csv.writer(f,delimiter=";")

这篇关于在python 2或python 3中编写csv文件的便携方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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