问题:
Traceback (most recent call last): File "test.py", line 23, in data_loader = CreateDataLoader(opt) File "D:\wGAN\mc-gan2\data\data_loader.py", line 48, in CreateDataLoader data_loader.initialize(opt) File "D:\wGAN\mc-gan2\data\data_loader.py", line 445, in initialize dict_inds = pickle.load(open(test_dict)) TypeError: a bytes-like object is required, not 'str'
原因:
open默认打开的是bytes-like文件,而不是str;如果要打开str,则必须使用
open(test_dict, 'r')
例如,
#open text file in read mode
text_file = open("D:/data.txt", "r")
#read whole file to a string
data = text_file.read()
#close file
text_file.close()
print(data)
"""
输出data.txt中的内容,例如,
This is a test from data.txt
"""
本文结束
参考资料:
TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3 - Stack Overflow
You opened the file in binary mode:
with open(fname, 'rb') as f:
This means that all data read from the file is returned as bytes
objects, not str
. You cannot then use a string in a containment test:
if 'some-pattern' in tmp: continue
You'd have to use a bytes
object to test against tmp
instead:
if b'some-pattern' in tmp: continue
or open the file as a textfile instead by replacing the 'rb'
mode with 'r'
.