我正在尝试将字典invIndex
写入文本文件。我发现了以下帖子:
我写了这些文字:
import csv
f = open('result.csv','wb')
w = csv.DictWriter(f,invIndex)
w.writerow(invIndex)
f.close()
当我到达此行时:w.writerow(invIndex)
,我收到此错误:
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' does not support the buffer interface
如何正确地将字典写入文本文件。
答案 0 :(得分:2)
在Python 3中,csv编写者和读者期望文本流,但open(.., 'wb')
(或更确切地说,b
创建一个字节流)。尝试:
import csv
invIndex = [
{'fruit': 'apple', 'count': '10'},
{'fruit': 'banana', 'count': '42'}]
with open('result.csv', 'w', encoding='utf-8') as f:
w = csv.DictWriter(f, invIndex[0].keys())
w.writeheader()
w.writerows(invIndex)
将utf-8
替换为您要使用的encoding。它会写一个像
fruit,count
apple,10
banana,42