我最近迁移到了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的问题,但这一小段话让我很不爽。
就像已经提到的,你正在以二进制模式读取文件,然后创建一个字节列表。在你下面的for循环中,你正在比较字符串和字节,这就是代码失败的地方。
在添加到列表中的同时对字节进行解码应该是可行的。修改后的代码应该如下。
with open(fname, 'rb') as f:
lines = [x.decode('utf8').strip() for x in f.readlines()]
bytes 类型是在 Python 3 中引入的,这就是为什么你的代码在 Python 2 中可以工作。在Python 2中,没有字节的数据类型。
>>> s=bytes('hello')
>>> type(s)
<type 'str'>
为这个小例子。 输入socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data);
mysock.close()
前面加上"b"。 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n'。 解决了我的问题