1. 程式人生 > >can't use a string pattern on a bytes-like object錯誤和must be str, not bytes錯誤

can't use a string pattern on a bytes-like object錯誤和must be str, not bytes錯誤

哎,新手使用Python真是痛苦,步步艱辛步步淚!寫了四行程式,出來兩個錯誤。下面記錄錯誤和解決方法

===============================================================================================

error 1:

re.search(r'pattern',data.decode())

can't use a string pattern on a bytes-like object

solution:

將bytes-like 物件轉換成string物件:re.search(r'pattern',data.decode())

=========================================================================================

error 2:

fo=open('sourcefile.txt','w')

fo.wirte(data)

TypeError: must be str, not bytes

solution:將fo開啟為二進位制寫入方式:fo=open('sourcefile.txt','wb')