Skip to main content
 首页 » 编程设计

python之"unicode argument without an encoding"使用 extend 向 bytearray 添加一个字节时

2024年11月01日12fff_TT

我正在尝试从二进制文件构建字节数组,如下所示:

myArr = bytearray() 
with open(r"C:\Users\User\MyFileName.bin", "rb") as f: 
        byte = f.read(1) 
        while byte: 
            myArr.extend(byte) 
            byte = f.read(1) 

这导致:

Traceback (most recent call last): 
  File "myScriptName.py", line 20, in testByteParsing 
    myArr.extend(byte) 
TypeError: unicode argument without an encoding 

上面有什么问题吗?

FWIW,我正在使用 IronPython

请您参考如下方法:

通过查看 IronPython's bytearray source code我可以看到 extend 方法在内部调用了 GetBytes 方法:

public void extend(object seq) { 
    extend(GetBytes(seq)); 
} 

实际上,GetBytes 方法在给定 string 时硬连接到 except。

private static IList<byte>/*!*/ GetBytes(object/*!*/ value) { 
    ListGenericWrapper<byte> genWrapper = value as ListGenericWrapper<byte>; 
    if (genWrapper == null && value is IList<byte>) { 
        return (IList<byte>)value; 
    } 
 
    if (value is string || value is Extensible<string>) { 
        throw PythonOps.TypeError("unicode argument without an encoding"); 
    } 
 
    List<byte> ret = new List<byte>(); 
    IEnumerator ie = PythonOps.GetEnumerator(value); 
 
    while (ie.MoveNext()) { 
        ret.Add(GetByte(ie.Current)); 
    } 
    return ret; 
    } 

所以我建议使用 ord() 将从文件中读取的字节转换为 0-255 范围内的整数值。函数,然后使用 append 将其插入到 bytearray 中。

你的代码可以保持这样:

myArr = bytearray() 
with open(r"C:\Users\User\MyFileName.bin", "rb") as f: 
    byte = f.read(1) 
    while byte: 
        myArr.append(ord(byte)) 
        byte = f.read(1) 

这有点丑陋,我认为他们按照某些 .NET 库的限制以这种方式实现。

也许更熟悉 IronPython 的人可以提供更优雅的解决方案。

希望这对您有所帮助!