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

问题:

Traceback (most recent call last):
  File "test.py", line 23, in <module>
    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'.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值