Python异常:TypeError: a bytes-like object is required, not ‘str’
import json
str = [{"userName" : "UserPython", "age" : 20}, (2, 3), 1]
with open("jsonTest.txt", "wb") as fp:
json.dump(str, fp = fp)
异常分析:open(“jsonTest.txt”, “wb”)指定文件以二进制写模式打开,所以需要以二进制写入,不能写入字符串,而上面代码中str是一个列表字符串,所以报异常。
解决方法:因为上面代码中str是列表字符串,所以将open()函数中的打开文件方式改为“w”写模式即可
import json
str = [{"userName" : "UserPython", "age" : 20}, (2, 3), 1]
with open("jsonTest.txt", "w") as fp:
json.dump(str, fp = fp)