开发者

How to do a safe binary comparison in Python?

开发者 https://www.devze.com 2023-03-05 07:14 出处:网络
I have the following piece of code that is throwing a warning: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

I have the following piece of code that is throwing a warning:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

try:
    f = open_old(filename, "rb")
    aBuf = f.read(4)
    f.close()
except:
    aBuf=b''
if aBuf[:3] == b'\xEF\xBB\xBF':
    print("...")

What is the proper way of reading 3 bytes from the file and checking their values.

I am looking for a solution that would开发者_如何转开发 work properly in Python 2.6 and newwer (including 3.x).


The solution is to convert the string to bytes after you read it: aBuf = bytes(f.read(4)).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号