Python:向文件写入和读取二进制数据块

2023-12-27

我正在编写一个脚本,它将另一个 python 脚本分解为块并使用 pycrypto 来加密这些块(到目前为止我已经成功完成了所有这些),现在我将加密的块存储到一个文件中,以便解密器可以读取它并执行每个块。加密的最终结果是二进制输出的列表(类似于blocks=[b'\xa1\r\xa594\x92z\xf8\x16\xaa',b'xfbI\xfdqx|\xcd\xdb\x1b\xb3',etc...]).

将输出写入文件时,它们最终都会变成一个巨行,因此在读取文件时,所有字节都会返回到一个巨行中,而不是原始列表中的每个项目。我还尝试将字节转换为字符串,并添加'\n'在每个末尾,但问题是我仍然需要字节,并且我不知道如何撤消字符串以获取原始字节。

总结一下,我希望:将每个二进制项写入文件中的单独行,以便我可以轻松读取数据并在解密中使用它,或者我可以将数据转换为字符串并在解密中撤消string 来获取原始的二进制数据。

以下是写入文件的代码:

    new_file = open('C:/Python34/testfile.txt','wb')
    for byte_item in byte_list:
        # This or for the string i just replaced wb with w and
        # byte_item with ascii(byte_item) + '\n'
        new_file.write(byte_item)
    new_file.close()

以及读取文件:

    # Or 'r' instead of 'rb' if using string method
    byte_list = open('C:/Python34/testfile.txt','rb').readlines()

文件是没有任何隐含结构的字节流。如果你想加载二进制 blob 列表,那么你应该存储一些额外的元数据来恢复结构,例如,你可以使用网络字符串格式 http://cr.yp.to/proto/netstrings.txt:

#!/usr/bin/env python
blocks = [b'\xa1\r\xa594\x92z\xf8\x16\xaa', b'xfbI\xfdqx|\xcd\xdb\x1b\xb3']

# save blocks
with open('blocks.netstring', 'wb') as output_file:
    for blob in blocks:
        # [len]":"[string]","
        output_file.write(str(len(blob)).encode())
        output_file.write(b":")
        output_file.write(blob)
        output_file.write(b",")

读回它们:

#!/usr/bin/env python3
import re
from mmap import ACCESS_READ, mmap

blocks = []
match_size = re.compile(br'(\d+):').match
with open('blocks.netstring', 'rb') as file, \
     mmap(file.fileno(), 0, access=ACCESS_READ) as mm:
    position = 0
    for m in iter(lambda: match_size(mm, position), None):
        i, size = m.end(), int(m.group(1))
        blocks.append(mm[i:i + size])
        position = i + size + 1 # shift to the next netstring
print(blocks)

作为替代方案,您可以考虑您的数据的 BSON 格式 http://bsonspec.org/ or ascii 装甲格式 https://www.rfc-editor.org/rfc/rfc4880#section-6.2.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:向文件写入和读取二进制数据块 的相关文章

随机推荐