TypeError:在Python3中写入文件时,需要类似bytes的对象,而不是str

2024-04-20 06:45:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近迁移到Py 3.5。 这段代码在Python2.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问题,但这一点声明困扰着我。


Tags: 代码inpyforifwithlinesome
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',将文件作为文本文件打开。

正如前面提到的,您正在以二进制模式读取文件,然后创建字节列表。在下面的for循环中,您将字符串与字节进行比较,这就是代码失败的地方。

在添加到列表时解码字节应该可以工作。更改后的代码应如下所示:

with open(fname, 'rb') as f:
    lines = [x.decode('utf8').strip() for x in f.readlines()]

bytes类型是在Python 3中引入的,这就是代码在Python 2中工作的原因。在Python2中没有字节的数据类型:

>>> s=bytes('hello')
>>> type(s)
<type 'str'>

您可以使用.encode()对字符串进行编码

示例:

'Hello World'.encode()

相关问题 更多 >