Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

python - TypeError:需要类似字节的对象,而在Python3中写入文件时不是'str'(TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3)

I've very recently migrated to Py 3.5.

(我最近已经迁移到Py 3.5。)

This code was working properly in Python 2.7:

(这段代码在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

After upgrading to 3.5, I'm getting the:

(升级到3.5后,我得到了:)

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

error on the last line (the pattern search code).

(最后一行错误(模式搜索代码)。)

I've tried using the .decode() function on either side of the statement, also tried:

(我试过在语句的任何一侧使用.decode()函数,也尝试过:)

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

- to no avail.

(-无济于事。)

I was able to resolve almost all 2:3 issues quickly, but this little statement is bugging me.

(我能够很快解决几乎所有的2:3问题,但是这个小小的声明困扰着我。)

  ask by masroore translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 .

(这意味着从文件读取的所有数据都以bytes对象而不是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:

(您必须使用bytes对象来针对tmp进行测试:)

if b'some-pattern' in tmp: continue

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

(或以文本文件形式打开文件,而不是用'r'代替'rb'模式。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...