TypeError:在 Python3 中写入文件时需要一个类似字节的对象,而不是“str"

2022-01-31 00:00:00 python python-3.x string file byte

问题描述

我最近迁移到 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'.

相关文章