TypeError:在Python3中写入文件时需要一个类似字节的对象,而不是'str' [英] TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3
问题描述
我最近已迁移到Py 3.5。
此代码在Python 2.7中正常工作:
I've very recently migrated to Py 3.5. This code was working properly in 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之后,我得到了:
After upgrading to 3.5, I'm getting the:
TypeError: a bytes-like object is required, not 'str'
最后一行错误(模式搜索代码)。
error on the last line (the pattern search code).
我尝试在语句的任何一侧使用 .decode()
函数,也尝试过:
I've tried using the .decode()
function on either side of the statement, also tried:
if tmp.find('some-pattern') != -1: continue
-无济于事。
我能够迅速解决几乎所有的2:3问题,但是这个小问题困扰着我。
I was able to resolve almost all 2:3 issues quickly, but this little statement is bugging me.
推荐答案
您以二进制模式打开文件:
You opened the file in binary mode:
with open(fname, 'rb') as f:
这意味着从文件读取的所有数据均以<$返回c $ c> bytes 个对象,而不是 str
个对象。然后,您不能在遏制性测试中使用字符串:
This means that all data read from the file is returned as bytes
objects, not str
. You cannot then use a string in a containment test:
if 'some-pattern' in tmp: continue
您必须使用 bytes
对象对 tmp
代替:
You'd have to use a bytes
object to test against tmp
instead:
if b'some-pattern' in tmp: continue
或以文本文件形式打开文件,而不是替换'rb'
模式,并带有'r'
。
or open the file as a textfile instead by replacing the 'rb'
mode with 'r'
.
这篇关于TypeError:在Python3中写入文件时需要一个类似字节的对象,而不是'str'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!