Python中dic写入txt报错:a bytes-like object is required, not 'str'
dic = {2:'bob',3:'alice'}
output = open('/Users/Air/itchat/push.txt','wb')
for i in dic:
print (i,dic[i])
write_str = str(i) + ' ' + str(dic[i]) + '\n'
print(type(write_str))
output.write(write_str)
output.close()
PyCharm运行报错如下:
2 bob
<class 'str'>
Traceback (most recent call last):
File "/Users/Air/itchat/test.py", line 8, in <module>
output.write(write_str)
TypeError: a bytes-like object is required, not 'str'
Process finished with exit code 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
打开方式改成w,不要用wb。b代表二进制
用wb打开,需要encode
`dic = {2:'bob',3:'alice'}
output = open('/Users/Air/itchat/push.txt','wb')
for i in dic:
output.close()`