国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

dict - Error when writing dic to txt in Python: a bytes-like object is required, not 'str'
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-06-30 09:55:31
0
2
1681
 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中文網(wǎng)
PHP中文網(wǎng)

認(rèn)證0級講師

reply all(2)
扔個三星炸死你

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

阿神

用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()`

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template