You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python替换二进制文件字节报错:'bytes'对象不支持元素赋值

解决TypeError: 'bytes' object does not support item assignment问题

错误原因

Python中的bytes对象是不可变类型,你通过struct.unpack得到的x属于bytes类型,直接对其元素赋值会触发上述错误。

解决方案

将不可变的bytes转换为可变的bytearray,修改完成后再重新打包数据并写回文件(满足你替换二进制文件字节的需求)。同时要注意字符串与字节的编码转换,避免类型不匹配。

修改后的完整代码

#!/usr/bin/env python3
import struct

def generate():
    with open("a.bin","wb") as fd:
        for i in range(0,36):
            fd.write(i.to_bytes(1,"little"))
    return

def replace(buf, target):
    # 将字符串转为字节,避免类型不匹配
    target_bytes = target.encode('utf-8')
    # 取两者长度的最小值,防止索引越界
    replace_len = min(len(buf), len(target_bytes))
    for i in range(replace_len):
        buf[i] = target_bytes[i]
    return

def main():
    generate()

    with open("a.bin","rb") as fd:
        data = fd.read()

    s = struct.Struct("<32s I")
    x, y = s.unpack(data)
    print("修改前的x:", x)
    
    # 将bytes转为可变的bytearray
    x = bytearray(x)
    target = "hello world"
    replace(x, target)
    print("修改后的x:", x)

    # 重新打包数据并写回文件
    new_data = s.pack(x, y)
    with open("a.bin", "wb") as fd:
        fd.write(new_data)
    return

main()

关键修改说明

  • 使用bytearray(x)将不可变的bytes转为可变类型,支持元素赋值
  • 把字符串target通过encode('utf-8')转为字节类型,保证与bytearray的元素类型一致
  • 添加长度判断min(len(buf), len(target_bytes)),避免因目标字符串过长导致索引越界
  • 新增重新打包并写回文件的逻辑,完成二进制文件的字节替换操作

内容的提问来源于stack exchange,提问作者lucky1928

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:54:51