python - Error in writing a dictionary to a file -
i trying write dictionary invindex
text file. found following post:
and wrote these lines:
import csv f = open('result.csv','wb') w = csv.dictwriter(f,invindex) w.writerow(invindex) f.close()
when reach line: w.writerow(invindex)
, error:
traceback (most recent call last): file "<stdin>", line 1, in <module> file "c:\python33\lib\csv.py", line 153, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) typeerror: 'str' not support buffer interface
how can write dictionary text file correctly.
in python 3, csv writers , readers expect text stream, open(.., 'wb')
(or more precisely, b
creates byte stream). try:
import csv invindex = [ {'fruit': 'apple', 'count': '10'}, {'fruit': 'banana', 'count': '42'}] open('result.csv', 'w', encoding='utf-8') f: w = csv.dictwriter(f, invindex[0].keys()) w.writeheader() w.writerows(invindex)
replace utf-8
encoding want use. write file like
fruit,count apple,10 banana,42
Comments
Post a Comment