程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

"TypeError: a bytes-like object is required, not 'str'" when handling file content in Python 3

发布于2025-01-05 08:55     阅读(803)     评论(0)     点赞(4)     收藏(0)


I've very recently migrated to Python 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

But in 3.5, on the if 'some-pattern' in tmp: continue line, I get an error which says:

TypeError: a bytes-like object is required, not 'str'

I was unable to fix the problem using .decode() on either side of the in, nor could I fix it using

    if tmp.find('some-pattern') != -1: continue

What is wrong, and how do I fix it?


解决方案


You opened the file in binary mode:

with open(fname, 'rb') as f:

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

You'd have to use a bytes object to test against tmp instead:

if b'some-pattern' in tmp: continue

or open the file as a textfile instead by replacing the 'rb' mode with 'r'.



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/2046770/28c0f784bd4e8b1ec2a4/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)