我最近迁移到 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 后,我得到了:
TypeError: a bytes-like object is required, not 'str'
错误在最后一行(模式搜索代码)。
我尝试在语句的任一侧使用 .decode()
函数,也尝试过:
if tmp.find('some-pattern') != -1: continue
-无济于事。
我能够快速解决几乎所有 Python 2 到 Python 3 的问题,但是这个小语句让我很烦。
最佳答案
您以二进制模式打开文件:
with open(fname, 'rb') as f:
这意味着从文件中读取的所有数据都返回为 bytes
对象,而不是 str
。然后你不能在包含测试中使用字符串:
if 'some-pattern' in tmp: continue
您必须使用 bytes
对象来针对 tmp
进行测试:
if b'some-pattern' in tmp: continue
或将文件作为文本文件打开,方法是将 'rb'
模式替换为 'r'
。
关于python - 在 Python 3 中写入文件时,TypeError : a bytes-like object is required, 不是 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054527/