csv.writerows()在每个

2024-05-16 18:59:35 发布

您现在位置:Python中文网/ 问答频道 /正文

这是O'Reilly Cookbook(截断数据集)中的一个例子

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中时,每一行之间都有空行。同样,如果我用记事本++打开它。

但是,如果我more来自命令行,则\n不会出现。

我在一个文件的末尾看到了另一个关于A \n的问答,但这一个是关于每行末尾的A \n。(我不明白为什么more没有给出\n。)

我计划把文件带到OpenOffice Calc中


Tags: 文件csv数据datetimemoresymbolchange
3条回答

这是一个额外的回车,这是一个Windows特有的问题,与Python 2/3的差异无关。如果在Notepad++中打开文件并启用Show all characters,您将看到以下内容:

Symbol,Price,Date,Time,Change,Volume[CR]
[CR][LF]
AA,39.48,6/11/2007,9:36am,-0.18,181800[CR]
[CR][LF]
AIG,71.38,6/11/2007,9:36am,-0.15,195500[CR]
[CR][LF]

这是因为Windows上的Python正在将以'\n'结尾的行转换为'\r\n',而writerows()函数已经将'\r\n'添加到每行的末尾。发生了什么事:

  1. csv.writerows()写入适当的数据行,然后以'\r\n'结束该行
  2. Python的内部处理(因为您在Windows上)看到了行尾“\n”,并认为需要将其更改为'\r\n'。所以你得到了'\r\r\n'

您看不到打印到控制台有问题的原因是,它没有将多余的'\r'作为一个新行进行检测,而Excel和Notepad++就是这样。

对于Python 3,您应该使用newline=''选项,如本文所述:https://docs.python.org/3/library/csv.html

csv.writer(csvfile, dialect='excel', **fmtparams)

Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline='' [1].

我在WindowsforPython3上遇到了这个问题。我试图在打开文件时更改newline参数,但它在newline=''中工作正常。

newline=''添加到open()方法,如下所示:

with open('stocks2.csv','w', newline='') as f:
    f_csv = csv.DictWriter(f, headers)
    f_csv.writeheader()
    f_csv.writerows(rows)

它会有魅力的。

希望有帮助。

此问题仅在Windows上的Python中出现。

在Python v3中,需要在open调用中添加newline=':

Python 3.3 CSV.Writer writes extra blank rows

在Python v2上,在传递给csv之前,需要在open()调用中以二进制形式打开文件

换行

with open('stocks2.csv','w') as f:

致:

with open('stocks2.csv','wb') as f:

会解决问题的

有关此问题的详细信息,请访问:

CSV in Python adding an extra carriage return

相关问题 更多 >