先介绍一下 python bytes和str两种类型转换的函数encode(),decode()
str通过encode()方法可以编码为指定的bytes
bytes通过decode()方法可以将bytes编码为str
举个栗子
fo =open("foo.txt","wb")
str ="www.room.com!Very good site!"
fo.write(str)
fo.close()
运行之后报错:
Traceback (most recent call last): File "E:/Python练习/Tony.py", line 6, info.write(str)
TypeError: a bytes-like object is required, not 'str' (需要的是bytes数据类型,不是str)
修改:
fo=open("foo.txt","wb")
str ="www.room.com!Very good site!"
fo.write(str.encode())
fo.close()
运行正确