Skip to content Skip to sidebar Skip to footer

Error In Writing A Dictionary To A File

I am trying to write a dictionary invIndex to a text file. I found the following post: and I wrote these lines: import csv f = open('result.csv','wb') w = csv.DictWriter(f,invInde

Solution 1:

In Python 3, csv writers and readers expect a text stream, but open(.., 'wb') (or more precisely, the b creates a byte stream). Try:

import csv
invIndex = [
  {'fruit': 'apple',  'count': '10'},
  {'fruit': 'banana', 'count': '42'}]
withopen('result.csv', 'w', encoding='utf-8') as f:
    w = csv.DictWriter(f, invIndex[0].keys())
    w.writeheader()
    w.writerows(invIndex)

Replace utf-8 with the encoding you want to use. It will write a file like

fruit,count
apple,10
banana,42

Post a Comment for "Error In Writing A Dictionary To A File"