无法以Python格式导出CSV格式

时间:2016-08-30 05:34:52

标签: python python-3.x csv pandas jupyter

我正在尝试从Jupyter笔记本导出到CSV文件。即使我测试从文档中复制粘贴的示例(见下文),我也得到一个“'str'对象不可调用”错误消息。我无休止地摆弄参数。使用Pandas数据帧也会发生同样的事情,我尝试使用to_csv。

基本上:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile)

产量

    TypeError                                 Traceback (most recent call last)
<ipython-input-169-cc34b7e892ee> in <module>()
  1 import csv
  2 with open('eggs.csv', 'w', newline='') as csvfile:
----> 3     spamwriter = csv.writer(csvfile)

TypeError: 'str' object is not callable

我是编码的新手,所以我真的不知道如何解决这一问题......任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

只有在csv.writer是字符串的情况下才能解释您看到的错误。这会重新创建您的错误:

In [1]: import csv

In [2]: csv.writer = 'test'   # <- cause error

In [3]: %paste
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile)

## -- End pasted text --
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-cc34b7e892ee> in <module>()
      1 import csv
      2 with open('eggs.csv', 'w', newline='') as csvfile:
----> 3     spamwriter = csv.writer(csvfile)

TypeError: 'str' object is not callable

我猜你要么在像Spyder这样的环境中工作,默认情况下会让一个会话保持活动状态以便运行代码,或者你正在尝试使用像IPython或Jupyter笔记本这样的REPL。在某些时候,您错误地为csv.writer分配了一个新值。如果您重置环境,问题就会消失,因为您的代码没有任何问题。

要重置,对于IPython或Spyder,只需退出并重新开始。对于Jupyter笔记本,从菜单中选择“Kernel | Restart”。

相关问题