这是我的密码:
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的原因是,我必须将多个数据文件写入同一个文件。我正在使用计数来检查它是否是第一次写入。
发布于 2016-08-21 15:46:37
选项quoting=3
等效于quoting=csv.QUOTE_NONE
。这是一种从不引用字段的指令。如果任何字段包含分隔符(逗号),则必须转义逗号。但是,没有转义符集,这会引发一个错误。csv报价常量的文档
例如,可以设置转义符df.to_csv(f,index=False, quoting=3, escapechar=r'\')
,使用反斜杠来转义出现的任何逗号,也可以使用不同的值引用。quoting=csv.QUOTE_MINIMAL
(或quoting=0
)只在需要引号的字段周围使用引号。
为了给出一个具体的例子,假设您有一个有两行两列的dataframe:
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"\"
可以得到:("\“用来转义逗号)
2015,eggs and spam
2016,eggs\, bacon and spam
但是有了quoting=3
,没有逃避现实,你就会有一个错误。
最好的解决方案是使用quoting=0
https://stackoverflow.com/questions/39064668
复制相似问题