python 按原样将字符串转换为bytes对象

m2xkgtsf  于 2023-06-04  发布在  Python
关注(0)|答案(2)|浏览(211)

如何将一个字符串转换为一个bytes对象 *as *,即而不进行编码我不能在这里使用.encode(),因为它会在保存后损坏我的二进制文件。

filedata = pathlib.Path('file.bin').read_bytes()
# since i can't modify a bytes object, i should convert it to a string, should I?
data = ''
for i in filedata:
    data += chr(i) if isinstance(i, int) else i
data[3] = '\x01'
data += '\x58\x02\x0C\x80\x61\x39\x56\x18\x55\x61\x89\x42\x42\x16\x46\x17\x54\x70\x10\x58\x60\x10\x10\x01\x75\x10\xF0\xC0\x00\x01\x00\x02\x00\xC0\x00\xD0\x00\x01\x00\xC4\x00\x01\x00\x02\x00\x01\x00\x00\x02\x00\x00\x00'
pathlib.Path('result.bin').write_bytes(data.encode()) # doesn't work as it should

因此,与此相反:

58 02 0C 80 61 39 56 18 55 61 89 42 42 16 46 17 54 70 10 58 60 10 10 01 75 10 F0 C0 00 01 00 02 00 C0 00 D0 00 01 00 C4 00 01 00 02 00 01 00 00 02 00 00 00

我得到了这个:

58 02 0C C2 80 61 39 56 18 55 61 C2 89 42 42 16 46 17 54 70 10 58 60 10 10 01 75 10 C3 B0 C3 80 00 01 00 02 00 C3 80 00 C3 90 00 01 00 C3 84 00 01 00 02 00 01 00 00 02 00 00 00

我尝试修改一个bytes对象本身,但总是得到这样的错误:
TypeError:'bytes'对象不支持项赋值

xjreopfe

xjreopfe1#

如何将字符串按原样转换为bytes对象,即而不进行编码
你不能。这是一个自相矛盾的术语--从Python 3开始。
一个 string 是一个文本字符序列。想想字母、标点符号、空格,甚至控制字符。一个 bytes 对象是一个8位数字序列。这两个序列如何相关是一个编码问题。这是没有办法的事。
文本字符应被视为抽象实体。例如,字母A是存在的。没有与之相关的数字 * 本身 *。(在内部,它由Unicode码位表示,这是一个数字,但这是一个实现细节。
在上面的代码中,你在阅读字节和写字节,在这中间你想操作字节流:更改其中一个数字,添加其他数字。
Python bytes在这方面与str没有什么不同:它们都是不可变类型。如果你像上面一样做了同样的事情,但是用的是一个字符串,你会得到同样的错误:

>>> s = 'abcd'
>>> s[3] = 'x'
TypeError: 'str' object does not support item assignment

也就是说,字符串不支持就地字符操作。但还有其他方法可以达到同样的效果。另一方面,就地字节操作 * 是 * 支持的-可以说是因为它是一个比字符串更常见的用例。您只需要使用bytearray而不是bytes

>>> data = bytearray(b'\x00\x01\x02\x03\x04')
>>> data[3] = 255
>>> print(data)
bytearray(b'\x00\x01\x02\xff\x04')

然后你就可以把它写入一个文件,而不需要任何编码:

pathlib.Path('result.bin').write_bytes(data)

(Note bytes文字必须以b为前缀。

kqlmhetl

kqlmhetl2#

感谢John(约翰):

filedata = bytearray(pathlib.Path(sys.argv[1]).read_bytes())
# filedata = bytearray(open(sys.argv[1], 'rb').read()) also works
filedata[1] = 255 # modifying a single byte (0 - 255)
filedata[0:1] = b'\xff' # inserting bytes
filedata.extend(255) # appending one single byte
filedata.extend(filedata2) # appending another array of bytes (bytearray object)
filedata.extend(b'\xff\xff') # appending bytes
filedata.extend([255, 255]) # appending bytes too
pathlib.Path(sys.argv[1]).write_bytes(filedata) # write data to a file
# open(sys.argv[1], 'rb').write(filedata) should work too

这最初添加到问题的revision 5中。

相关问题