search

Home  >  Q&A  >  body text

dict - Error when writing dic to txt in Python: 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

PHP中文网PHP中文网2705 days ago1565

reply all(2)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-06-30 09:57:31

    Change the opening method to w, do not use wb. b stands for binary

    reply
    0
  • 阿神

    阿神2017-06-30 09:57:31

    用wb打开,需要encode

    `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.encode())

    output.close()`

    reply
    0
  • Cancelreply