我最近迁移到了 Python 3.5。此代码在 Python 2.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 后,我得到:
类型错误:需要一个类似字节的对象,而不是“str”
错误在最后一行(模式搜索代码)。
我试过在语句的两边使用 .decode()
函数并尝试过:
if tmp.find('some-pattern') != -1: continue
- 无济于事。
我能够快速解决几乎所有 Python 2 到 Python 3 的问题,但这个小声明让我很烦。
原文由 masroore 发布,翻译遵循 CC BY-SA 4.0 许可协议
您以二进制模式打开文件:
这意味着从文件中读取的所有数据都作为
bytes
对象返回,而不是str
。然后您不能在包含测试中使用字符串:您必须使用
bytes
对象来针对tmp
进行测试:或通过将
'rb'
模式替换为'r'
来将文件作为文本文件打开。