您当前的位置: 首页 >  Python
  • 0浏览

    0关注

    483博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python open: TypeError: a bytes-like object is required, not ‘str‘

高精度计算机视觉 发布时间:2022-04-19 16:28:30 ,浏览量:0

问题:

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'.

 

关注
打赏
1661664439
查看更多评论
立即登录/注册

微信扫码登录

0.0382s