【发布时间】:2016-01-08 08:41:36
【问题描述】:
我最近迁移到 Py 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
-无济于事。
我能够快速解决几乎所有 2:3 的问题,但是这个小声明让我很烦。
【问题讨论】:
-
为什么你以二进制模式打开文件却把它当作文本?
-
@MartijnPieters 感谢您发现文件打开模式!将其更改为文本模式解决了这个问题......尽管代码在 Py2k 中可靠地运行了很多年......
-
@masroore 请参阅:python.org/dev/peps/pep-0404/#strings-and-bytes
-
我也遇到了这个问题,我有一个请求
result = requests.get并尝试x = result.content.split("\n")。我对错误消息有点困惑,因为它似乎暗示result.content是一个字符串,而.split()需要一个类似字节的对象..?? ("需要一个类似字节的对象,而不是 'str"').. -
Martjin 是对的,您应该将
'rb'选项更改为'r'以将文件视为字符串
标签: python python-3.x string file byte