Trying to create a csv using python, and getting "list indices" error
<p>In my last question, I asked how to get python to assign a set of values to phrases in a csv files.  I was told to create a list of tuples, and this worked great.    </p>

<p>Currently my list, called clean_titles looks like this:</p>

<pre><code>[('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('a', 1),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('b', 2),
 ('c', 3),
 ('c', 3),
 ('c', 3),
 ('c', 3),
 ('c', 3)]
</code></pre>

<p>Now I want to take the list, and export it to as CSV file.  I want the name of the phrases in one column and the assigned number in another column.</p>

<pre><code>with open("fiancee_wordfreq.csv" , "wb") as f:
     writer = csv.writer(f)  
  for val in clean_titles:
     writer.writerow([val])
</code></pre>

<p>But I keep getting an error message that "list indices must be integers not unicode" </p>

<p>What am I doing wrong or what am I missing.  Thanks for your help. </p>

<p>(My answer is for Python3)</p>

<p>You are opening the file in "bytes" mode. It worked for me when I removed the "b" argument:</p>

<pre><code>with open("testabc.csv" , "w") as f:
  writer = csv.writer(f)  
  for val in clean_titles:
     writer.writerow(val)
</code></pre>

<p>Also, you can just use a built-in <code>writerows</code> function to be less verbose:</p>

<pre><code>with open("testabc.csv" , "w") as f:
  writer = csv.writer(f)  
  writer.writerows(clean_titles)
</code></pre>

python csv