csv.writerows()在每行之后放置换行符 [英] csv.writerows() puts newline after each row
问题描述
这是来自 O'Reilly Cookbook (截短的数据集)
This is an example from the O'Reilly Cookbook (truncated dataset)
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [{'Symbol': 'AA', 'Volume': 181800, 'Change': -0.18,
'Time': '9:36am', 'Date': '6/11/2007', 'Price': 39.48},
{'Symbol': 'AIG', 'Volume': 195500, 'Change': -0.15,
'Time': '9:36am', 'Date': '6/11/2007', 'Price': 71.38} ]
with open('stocks2.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
输出文件在每一行的末尾都有一个\n
,显然在末尾还有一个.当我将其导入Excel时,每行之间都会出现空白行.如果使用Notepad ++打开它也一样.
the output file has a \n
at the end of each line, and apparently one more at the end. When I bring it into Excel, I get blank lines between each row. The same if I open it with Notepad++.
但是,如果我从命令行输入more
,则\n
不会显示.
But, if I more
if from a command line, the \n
don't show up.
我在文件末尾看到了另一个关于\n
的问答(Q& A),但是在每行末尾有一个关于\n
的问答. (而且我不明白为什么more
不给出\n
.)
I saw another Q&A about a \n
at the end of a file - but this one is about a \n
at the end of each line. (And I don't see why more
doesn't give the \n
.)
我计划将文件导入OpenOffice Calc.
I plan to bring the file into OpenOffice Calc.
推荐答案
仅在Windows上的Python中会出现此问题.
This problem occurs only with Python on Windows.
在Python v3中,您需要按以下步骤在打开的调用中添加newline ='':
In Python v3, you need to add newline='' in the open call per:
在Python v2上,您需要在open()调用中使用"b"以二进制形式打开文件,然后再传递给csv
On Python v2, you need to open the file as binary with "b" in your open() call before passing to csv
更改线路
with open('stocks2.csv','w') as f:
收件人:
with open('stocks2.csv','wb') as f:
将解决问题
有关此问题的更多信息:
More info about the issue here:
这篇关于csv.writerows()在每行之后放置换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!