【问题标题】:TypeError: expected a character buffer object (while writing dictionary keys to text file)TypeError:期望一个字符缓冲区对象(在将字典键写入文本文件时)
【发布时间】:2016-09-11 04:49:11
【问题描述】:

以下代码不起作用:

with open("testfile.txt",'w') as fw:
    for key in a:
        fw.write(a[key])

以下是错误:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: expected a character buffer object`

以下代码有效:

with open('myfile.txt', 'w') as f:
    for key, value in a.items():
        f.write('%s:%s\n' % (key, value))

有人可以帮我理解第一个区块出了什么问题吗?

【问题讨论】:

  • 你能发布a字典值吗
  • a = {1:2,2:3,3:4}

标签: python python-2.7 file dictionary


【解决方案1】:

正如错误消息所说:您只能将字符缓冲区对象写入文件。例如string。但是,您的字典中的条目是 ints - 它们不是字符缓冲区对象。因此,您必须首先将值转换为字符串,然后将其写入文件,例如可以通过'%d\n' % a[key]'{0]\n'.format(a[key]) 完成此转换。

您实际上可以使用'%s\n' % a[key],即使字典中的元素不是整数,它也可以工作。 python中的%s表示转换是使用str()函数完成的,这与C中的用法不同,因为在C中%s表示格式化一个以null结尾的字符串。你可以在你的第二个程序中观察到这一点,我首先认为你字典中的元素是strings。

【讨论】:

  • 这有帮助。非常感谢!
猜你喜欢
  • 2012-09-17
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2015-03-05
  • 2019-11-27
  • 2019-06-22
相关资源
最近更新 更多