先介紹一下 python bytes和str兩種類型轉(zhuǎn)換的函數(shù)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數(shù)據(jù)類型,不是str)
修改:
fo=open("foo.txt","wb")
str ="www.room.com!Very good site!"
fo.write(str.encode())
fo.close()
運行正確