【问题标题】:Failing to export to CSV in Python, multiple formats无法在 Python 中导出为 CSV,多种格式
【发布时间】:2023-03-13 17:36:01
【问题描述】:

我正在尝试从 Jupyter 笔记本导出为 CSV 文件。即使我测试从文档中复制粘贴的示例(见下文),我也会收到“'str' object is not callable”错误消息。我无休止地摆弄参数。 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

我是编码新手,所以我真的不知道如何排除故障...有人可以帮忙吗?

【问题讨论】:

  • eggs.csv 中有什么?
  • 为什么我感觉没有显示完整的代码?
  • 当我在本地运行这个示例时,它可以在普通终端和 jupyter notebook 中运行。出现错误的原因是您可能安装了非标准 csv 模块,或者您在导入“csv”后运行了一些其他代码(例如 csv.writer = "egg.csv" 之类的代码)。我建议尝试打开一个新的 Jupyter 笔记本并重新运行这 3 行。
  • 完整代码?是的,我没有粘贴我的整个 Jupyter 笔记本......无论如何,打开一个新笔记本解决了所有问题。我知道,很尴尬。

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


【解决方案1】:

您看到的错误只能在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 notebook 这样的 REPL 中进行试验。在某些时候,您错误地为csv.writer 分配了一个新值。如果您重置环境,问题就会消失,因为您的代码没有任何问题。

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

【讨论】:

  • 确实,重新启动内核修复了这一切。没有尝试过,我觉得很傻,所以我真的很感谢背景解释和缺乏 snark :)
猜你喜欢
  • 1970-01-01
  • 2019-07-04
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
相关资源
最近更新 更多