python - 在 Python 3 中写入文件时,TypeError : a bytes-like object is required, 不是 'str'

标签 python python-3.x string file byte

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

-无济于事。

我能够快速解决几乎所有 Python 2 到 Python 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'

关于python - 在 Python 3 中写入文件时,TypeError : a bytes-like object is required, 不是 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054527/

相关文章:

python - Django - 如何按特定顺序对对象进行排序?

python - 我如何轻松处理带括号的数字系列格式?

python - Python 3.4 上的 Flask Bug?如果应用程序包含相对导入,则开发服务器无法运行

python - 如何在 python 中使用正则表达式在特定单词之前获取特定模式的所有日期或关键字?

python - 在 anaconda mac 中安装 pygame 模块

python - Jupyter 实验室 "404 : Not Found You are requesting a page that does not exist!"

python - 如何将 f-string 与变量一起使用,而不是与字符串文字一起使用?

javascript - 从字符串中删除前导零和尾随零

c - 给函数内部的指针赋值

java - 删除数组中的元素,这些元素是 Java 中其他元素的子串