为什么to_csv会出错?

时间:2016-08-21 13:22:21

标签: python python-2.7 pandas dataframe

这是我的代码:

with open('myData', 'a') as f:
    if count1 == 1:
        df.to_csv(f,index=False, quoting=3 )
    else:
        df.to_csv(f,index=False, quoting=3 , header = False)


Error: need to escape, but no escapechar set

我该如何解决这个问题?我想我需要将引用改为无,并将字符引用到'"'。我是朝着正确的方向前进的吗?

这是完整的追溯:

---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-22-7b964e5d0ae8> in <module>()
 27         action.perform()
 28         html = browser.page_source
---> 29         ScrapePage(html)

<ipython-input-20-1d50d699fe76> in ScrapePage(html)
 56     with open('myData', 'a') as f:
 57         if count1 == 1:
---> 58             df.to_csv(f,index=False, quoting=3 )
 59         else:
 60             df.to_csv(f,index=False, quoting=3 , header = False)

C:\Anaconda2\lib\site-packages\pandas\core\frame.pyc in to_csv(self, path_or_buf, sep,
na_rep, float_format, columns, header, index, index_label, mode, encoding, compression,
quoting, quotechar, line_terminator, chunksize, tupleize_cols, date_format, doublequote,
escapechar, decimal, **kwds)

1330                                      escapechar=escapechar,
1331                                      decimal=decimal)
-> 1332         formatter.save()
1333 
1334         if path_or_buf is None:

C:\Anaconda2\lib\site-packages\pandas\core\format.pyc in save(self)
1504 
1505             else:
-> 1506                 self._save()
1507 
1508         finally:

C:\Anaconda2\lib\site-packages\pandas\core\format.pyc in _save(self)
1604                 break
1605 
-> 1606             self._save_chunk(start_i, end_i)
1607 
1608     def _save_chunk(self, start_i, end_i):

C:\Anaconda2\lib\site-packages\pandas\core\format.pyc in _save_chunk(self, start_i, end_i)
1631                                         quoting=self.quoting)
1632 
-> 1633         lib.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer)
1634 
1635 # from collections import namedtuple

pandas\lib.pyx in pandas.lib.write_csv_rows (pandas\lib.c:19840)()

Error: need to escape, but no escapechar set

if: else:中写入csv的原因是因为我必须将多个数据帧写入同一个文件。我正在使用计数来检查它是否是第一次写入。

1 个答案:

答案 0 :(得分:2)

选项quoting=3相当于quoting=csv.QUOTE_NONE。这是一条永不引用字段的指令。如果任何字段包含分隔符(逗号),则必须转义逗号。但是没有escapechar设置,这会引发错误。 Documentation for csv quote constants

例如,您可以设置escapechar df.to_csv(f,index=False, quoting=3, escapechar=r'\'),以使用反斜杠来转义出现的任何逗号,或者您可以使用不同的值进行引用。 quoting=csv.QUOTE_MINIMAL(或quoting=0)将仅在需要它们的字段周围使用引号。

举一个具体的例子,假设你有一个包含两行和两列的数据框:

2015   "eggs and spam"
2016   "eggs, bacon and spam"

作为带quoting=0的csv文件,你得到(在包含逗号的字段周围使用引号)

2015,eggs and spam
2016,"eggs, bacon and spam"

使用quoting=3, escapechar=r"\"得到:(&#34; \&#34;用于转义逗号)

2015,eggs and spam
2016,eggs\, bacon and spam

但是使用quoting=3并且没有escapechar,您会收到错误。

最好的解决方案是使用quoting=0