gpt4 book ai didi

python - 将字节附加到字符串?

转载 作者:行者123 更新时间:2023-11-28 20:25:32 26 4
gpt4 key购买 nike

我有一个用 Python 打开的文件,我正在将其写入另一个输出文件。我需要它的文件大小是 16 的倍数,所以这就是我设计的:

 with open(input_file, 'rb') as infile:
with open(output_file, 'wb') as outfile:
while True:
input_chunk = infile.read(64)

if len(input_chunk) == 0:
break
elif len(input_chunk) % 16 > 0:
input_chunk.extend([0 for i in range(len(input_chunk) % 16)])

output_file.write(input_chunk)

不幸的是,它无法附加零:

AttributeError: 'str' object has no attribute 'extend'

首先,为什么我这里有一个字符串,而不是一个字节数组?我正在以二进制模式读取二进制文件。

其次,如果我正在处理一个字符串,我该如何将值为 0 的字节数写入该字符串的末尾?

最佳答案

First, why do I have a string here, rather than an array of bytes?

因为这就是 file.read 返回的...

Second, if I'm dealing with a string, how do I write a number of bytes with the value 0 to the end of that string?

你不能把它写到那个字符串上,因为字符串是不可变的。但是,您可以将其写入不同的字符串并通过连接创建新字符串:

>>> import struct
>>> input_chunk = 'foo bar baz'
>>> input_chunk + struct.pack('16B',*([0]*16))
'foo bar baz\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>

请注意,如果您知道您有 64 个字节并且您想要一个用空值填充的 80 字节的字符串,struct.pack 将自动用空值填充它:

struct.pack('80s',string_of_64_bytes)

For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. If a count is not given, it defaults to 1. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting string always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters).

关于python - 将字节附加到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14949737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com