Failing to export to CSV in Python, multiple formats
<p>I am trying to export to CSV files from a Jupyter notebook. Even when I test examples copy-pasted from the documentation (see below), I get a "'str' object is not callable" error message. I have fiddled endlessly with the parameters. The same thing happens with a Pandas dataframe and I try to use to_csv.</p>

<p>Basically:</p>

<pre><code>import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile)
</code></pre>

<p>yields</p>

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

TypeError: 'str' object is not callable
</code></pre>

<p>I'm new to coding, so I don't really know how to troubleshoot past this point...can anyone help?</p>

<p>The error you are seeing can only be explained if <code>csv.writer</code> is a string. This recreates your error:</p>

<pre><code>In [1]: import csv

In [2]: csv.writer = 'test'   # &lt;- 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)
&lt;ipython-input-3-cc34b7e892ee&gt; in &lt;module&gt;()
      1 import csv
      2 with open('eggs.csv', 'w', newline='') as csvfile:
----&gt; 3     spamwriter = csv.writer(csvfile)

TypeError: 'str' object is not callable
</code></pre>

<p>I'm guessing you are either working in an environment like Spyder which by default keeps a single session alive for code to run in, or you are experimenting in a REPL like IPython or a Jupyter notebook. At some point you mistakenly assigned a new value to  <code>csv.writer</code>. The problem will go away if you reset your environment, since there is nothing wrong with your code.</p>

<p>To reset, for IPython or Spyder just exit and start again. For Jupyter notebook select "Kernel|Restart" from the menu.</p>

python python-3.x csv pandas jupyter