a bytes-like object is required, not ‘str‘問題解決記錄
阿新 • • 發佈:2020-12-20
在除錯自底向上這篇論文程式碼時 由於作者是2018年程式設計在pythob2.7環境下,我在除錯時用了python3.8版本,出現:
經過網上查詢原因分析是Python2 和 Python3 的字串相容問題,資料檔案是在Python2下是序列化的,所以使用Python3讀取時,需要將‘str’轉化為’bytes’。
#新建一個類StrToBytes
class StrToBytes:
def __init__(self, fileobj):
self.fileobj = fileobj
def read(self, size):
return self.fileobj.read(size).encode()
def readline(self, size=-1):
return self.fileobj.readline(size).encode()
#原先
if os.path.exists(train_ids_file) and os.path.exists(val_ids_file):
train_imgids = pickle.load(open(train_ids_file))
val_imgids = pickle. load(open(val_ids_file))
#修改
if os.path.exists(train_ids_file) and os.path.exists(val_ids_file):
train_imgids = pickle.load(StrToBytes(open(train_ids_file)))
val_imgids = pickle.load(StrToBytes(open(val_ids_file)))
解決問題
即可正常從tsv檔案讀取了