TypeError:在 Python3 中写入文件时需要一个类似字节的对象,而不是“str" [英] TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

查看:26
本文介绍了TypeError:在 Python3 中写入文件时需要一个类似字节的对象,而不是“str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于TypeError:在 Python3 中写入文件时需要一个类似字节的对象,而不是“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆