0

我正在尝试将字典写入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

如何正确地将字典写入文本文件。

4

1 回答 1

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编码。它会写一个像

fruit,count
apple,10
banana,42
于 2013-07-07T11:29:39.957 回答