4

I am testing some really simple code with Python 3. For some reason, the following code generates an empty output, instead of writing a line

import csv

output = open('hello world.csv', 'w',newline='')
wr = csv.writer(output, quoting=csv.QUOTE_ALL)

wr.writerow('hello world')

If I try the commands in the interpreter, .writerow() returns a number. The following example is the one used in the documentation page:

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

1 回答 1

8

writeroweggs.csv实际上会写入行,但由于文件缓冲,您看不到它们。要查看文件中的某些内容,请关闭它或调用.flush()方法。如果您使用with-statement,则即使出现错误,文件也会自动关闭。

它没有记录(报告错误?)但writerow返回fileobj.write()方法的结果,即在这种情况下写入文件的字符数。

您应该将形成一行的字段序列传递给writerow方法:

writer.writerow(['field 1', 'field 2', 'etc'])

如果您传递一个字符串而不是列表,则该字符串被解释为一个字段序列,其中每个字段都是一个单独的字符:

#XXX this is probably not what you want, don't do it
writer.writerow('abc')
# -> a,b,c
于 2012-10-07T18:14:37.390 回答