title: Python: Writing Counter to a csv file
body: <p>I have a csv file of data that has the columns <code>‘number’</code>, <code>’colour’</code>, <code>’number2’</code>, <code>’foo’</code>, <code>’bar’</code>, which looks like:</p>
  
  <pre><code>12, red, 124, a, 15p
  14, blue, 353, c, 7g
  12, blue, 125, d, 65h
  12, red, 124, c, 12d
  </code></pre>
  
  <p>I want to count the number of times number, colour and number2 occur together, so for example, the output from the above list would be: <code>’12, red, 124 :2’,’14, blue, 353: 1’, ’12, blue, 125: 1’</code>. I’ve done this by using:</p>
  
  <pre><code>import csv
  datafile=open('myfile.csv','r')
  usefuldata=[] 
  for line in datafile: 
      usefuldata.append(line) 
  from collections import Counter
  outfile1=Counter((line[1],line[2],line[3]) for line in usefuldata)  
  print(outfile1)
  </code></pre>
  
  <p>This gives me :</p>
  
  <pre><code>Counter({(‘12’,’red’,’135’): 21, (‘15’,’blue’,’152’):18, (‘34’,’green’,’123’):16 etc})
  </code></pre>
  
  <p>Which is great, but I’d like to write this out to a file. I'd like the file to have 4 columns: number, colour, number2, and count. I realise this is a common question and I’ve tried a few different approaches suggested on other threads, but none have worked.</p>
  
  <pre><code>Newfile=open(‘newfile.csv’,’wb’)
  fieldnames=['a','b']
  csvwriter=csv.DictWriter(newfile, delimiter=',', fieldnames=fieldnames)
  csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
  for row in outfile1:
      csvwriter.writerow(row)
  </code></pre>
  
  <p>And </p>
  
  <pre><code>with open('newfile.csv','wb') as csvfile:
      fieldnames=['number','colour','number2']
      writer=csv.DictWriter(csvfile, fieldnames=fieldnames)
      writer.writeheader()
      writer.writerow(Counter((line[1],line[2],line[3]) for line in usefuldata))
      countwriter=csv.writer(csvfile, delimiter=', ')
      countwriter.writerow(outfile1)
  </code></pre>
  
  <p>Both give me the error </p>
  
  <pre><code>    return self.writer.writerow(self._dict_to_list(rowdict))
  TypeError: 'str' does not support the buffer interface
  </code></pre>
  
  <p>I've also tried using pickle:</p>
  
  <pre><code>import pickle
  with open('newfile.csv','wb') as outputfile:
      pickle.dump(outfile1, outputfile)
  </code></pre>
  
  <p>gives me gibberish files.</p>
  
  <p>My current attempt is to use</p>
  
  <pre><code>writer=csv.DictWriter(newfile, outfile1)
  for line in outfile1:
      writer.writerow(line)
  </code></pre>
  
  <p>but this gives me an error about fieldnames.</p>
  
  <p>I know this is a common question and I'm conscious that I'm only struggling because I really don't know what I'm doing- it has been a few years since I've used python and I've forgotten so much. Any help would be greatly appreciated.</p>