connected = struct.unpack('>B', data[15])[0]
使用struct.unpack的时候用python3运行就报下面的错误,但是用py2.7就不报错
TypeError: a bytes-like object is required, not 'int'
该回答引用ChatGPT
在Python 3中,struct.unpack函数的第一个参数需要一个表示字节序列的bytes对象,而不是一个整数。因此,如果你将一个整数传递给struct.unpack,会引发类型错误异常。
要解决这个问题,你需要将data变量转换为一个bytes对象,例如:
connected = struct.unpack('>B', bytes([data[15]]))[0]
这里使用了bytes函数将单个整数转换为bytes对象。请注意,bytes函数的参数应该是一个序列,因此我们传递一个包含单个整数的列表[data[15]]。
这个代码将会在Python 2和Python 3上都运行成功。
data[15]必须是个bytearray,不能是int
别讲py2不报错,py2的语法和py3的语法差太多了
今天在处理Python脚本的时候遇到了这样一个错误
TypeError: a bytes-like object is required, not ‘str’
我在处理用python处理一个文件读写的时遇到的,代码如下:
f = open("./hosts.txt",'r')
hosts = [ip.strip('\n') for ip in f]
f_write = open("./good_ip.txt", "wb")
for ip in hosts:
f_write.write(ip)
python3 对字符串和字节码进行了规范的定义:str和bytes。
在存储时数据是以字节码的形式存储的,但是Python3不会对str做隐式转换,所以我们需要手动对需要存储的字符串做转换:使用decode和encode
python3 使用
decode() bytes–>str
encode() str -->bytes
所以上面的代码改为下面这样即可:
f = open("./hosts.txt", 'r')
hosts = [ip.strip('\n') for ip in f]
f_write = open("./good_ip.txt", "wb")
for ip in hosts:
ip = ip.encode()
f_write.write(ip)