类型错误:在 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:
这意味着从文件中读取的所有数据都作为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'
.
这篇关于类型错误:在 Python3 中写入文件时需要类似字节的对象,而不是“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!