原创:+++++++++++++++++++++++++++++++
如果出现这样的错误,一般呢是Python2 与 Python 3 不兼容情况造成的:
例如:
with open(fname, 'rb') as f:
lines = [x.strip() for x in f.readlines()]
for line in lines:
tmp = line.strip().lower()
if 'some-pattern' in tmp: continue
# ... code
它会出现下面的错误类型:
TypeError: a bytes-like object is required, not 'str'
基于以上错误改正的方式有两种:
with open(fname, 'rb') as f:
if b'some-pattern' in tmp: continue
(1)在字符串之前添加 b
with open(fname, 'r') as f:
(2)将‘rb’读取改为‘r’读取。一般这样问题就解决了,如果出现 编码的错误,可以在打开方式后面加一个编码格式,
with open(fname, 'r',encoding='utf-8') as f:
同时还会出现别的一些问题:比如如何把一个str类型的字符串强制转化为二进制的形式,直接在前面加bin
例子如下:>>> bin(int('256', 10))
'0b100000000'
>>> str(int('0b100000000', 2))
'256'