我最近迁移到了Py3.5。这段代码在Python2.7中正常工作:
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
升级到3.5后,我得到了:
TypeError: a bytes-like object is required, not 'str'
最后一行(模式搜索代码)出错。
我尝试在语句的两侧使用.decode()
函数,也尝试了:
if tmp.find('some-pattern') != -1: continue
-无济于事。
我能够很快解决几乎所有的2:3问题,但这个小小的声明困扰着我。
您以二进制模式打开了文件:
with open(fname, 'rb') as f:
这意味着从文件读取的所有数据都作为bytes
对象返回,而不是str
。则不能在包含测试中使用字符串:
if 'some-pattern' in tmp: continue
您必须使用bytes
对象来针对TMP
进行测试:
if b'some-pattern' in tmp: continue
或者将'r'
模式替换为'r'
模式,将文件作为文本文件打开。