Python3:编写csv文件 [英] Python3: writing csv files

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

问题描述

我试图在Windows计算机上使用Python 3.2编写一个简单的CSV文件,但我没有运气。从 Python 3.2的csv模块文档

I'm trying to use Python 3.2 on a Windows computer to write a simple CSV file, however I'm having no luck. From the csv module documentation for Python 3.2:

>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ',
...                         quotechar='|', quoting=csv.QUOTE_MINIMAL)
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

一个文件,每行由字节序列 \r\r\\\
终止,因此看起来每行都有一个额外的空行,当你打开它,例如,MS Excel。这不是一个CSV文件。

produces a file with each line terminated by the byte sequence \r\r\n, so it looks like each line has an extra empty line when you open it with, e.g., MS Excel. This is not a "CSV file".

注意,如果我尝试 Python 3.2中的Python 2.7的相关示例(其中最大的区别是'w' vs 'wb'为文件模式),我得到一个错误,当我尝试 spamWriter.writerow

Note, if I try the same example for Python 2.7 in Python 3.2 (where the big difference is 'w' vs 'wb' for the file mode), I get an error when I try spamWriter.writerow:


Traceback(最近一次调用):TypeError:'str'中的文件不支持缓冲区接口

Traceback (most recent call last): File "", line 1, in TypeError: 'str' does not support the buffer interface

如何在Windows计算机上从Python 3.2写一个简单的CSV文件?

How do I write a simple CSV file from Python 3.2 on a Windows computer?

推荐答案

文档说明应该使用 open('eggs.csv','w',newline ='')

http://docs.python.org/py3k/library/ csv.html#id2

这篇关于Python3:编写csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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